MySQL入门--基本操作

一、MySQL数据类型

1、正数类型

TINYINT:非常小的整数,类似于

SMALLINT:小整数

MEDIUMINT:中整数

INT,INTEGRE:整数

BIGINT:大整数

使用int数据类型

1)int:

2)int(M):M表示宽度,需要结合另外两个参数(unsigned,zerofill)进行使用。例如int(5) unsigned zerofill

2、浮点小数

float:4个字节

double:8个字节

使用float与double时

float(M, D), double(M, D):M表示总位数,D表示精度

3、定点小数,底层采用字符串

DECIMAL:

DECIMAL(M, D)

4、日期时间类型

data:表示日期

time:表示时间

datatime:表示日期与时间

year:表示年

timestamp:表示日期和时间。显示根据毫秒值算出来的本地化的日期时间

5、字符串

mysql没有单个字符的类型

char:定长字符串 :

​ char(1)/char(20)

varchar:变长字符串

​ varchar(M):最长不超过M个字符

text:长文本,一般用于存储文字较多且不常被检索的简介等信息

6、位类型(了解)

​ 二进制表示,BIT(M) 1-64

7、二进制类型

8、枚举类型

9、集合

二、常用语法

show databases;//查看当前存在的数据库

show tables;//查看存在的表

use 数据库名;//使用数据库

DDL

-- 1、查看当前mysql数据库管理软件中都有什么数据库
/*
DDL
*/
#注释
show databases;

#使用一个数据库
use test;

#创建一个新的数据库
create databases test;

#创建一个表
use test;
create table t_employee;
#或者 create test.t_employee;

#查看当前数据库中的表格
show tables;

#告知服务器当前客户端字符编码
set names gbk;
#查看某个表的数据
select * from t_employee;
#修改表的数据
update 表名 set 属性操作;
update t_employee set salary = salary + 1000;

#条件查询
select * from t_employee where 条件;
select * from t_employee where salary > 2000; 

#修改表的名字
rename table t_employee to new_table;
alter table t_employee rename new_table;

#增加一列
alter table t_employee add tel varchar(11);
#定义新增列的位置
alter table t_employee add tel varchar(11) first;
alter table t_employee add tel varchar(11) after 列名;

#修改列的属性
alter table t_employee modifiy gender char(2);

#修改列的位置
alter table t_employee modifiy address gender char(2)

DML
-- 1、查看当前mysql数据库管理软件中都有什么数据库
/*
DDL
*/
#注释
show databases;

#使用一个数据库
use test;

#创建一个新的数据库
create databases test;

#创建一个表
use test;
create table t_employee;
#或者 create test.t_employee;

#查看当前数据库中的表格
show tables;

#告知服务器当前客户端字符编码
set names gbk;
#查看某个表的数据
select * from t_employee;
#修改表的数据
update 表名 set 属性操作;
update t_employee set salary = salary + 1000;

#条件查询
select * from t_employee where 条件;
select * from t_employee where salary > 2000; 

#修改表的名字
rename table t_employee to new_table;
alter table t_employee rename new_table;

#增加一列
alter table t_employee add tel varchar(11);
#定义新增列的位置
alter table t_employee add tel varchar(11) first;
alter table t_employee add tel varchar(11) after 列名;

#修改列的属性
alter table t_employee modifiy gender char(2);

#修改列的位置
alter table t_employee modifiy address gender char(2)

三、约束与索引

3.1、关系型数据库设计规则

​ 遵循ER模型和三范式

​ E:代表实体,对应数据库中的一张表

​ R:表示关系

​ 三范式:列不能拆分

​ 唯一标识–数据不能重复,行与行应当能够区分

​ 关系引用主键

3.2、约束与索引的概念

​ 3.2.1、数据完整性是指数据的精确性与可靠性。

​ 数据完整性:

​ 实体完整性-----同一个表中不能存在两题套完全相同无法区分的记录

​ 域完整性-------例如年龄范围,性别范围

​ 引用完整性----员工所在部门,要在部门表中找到这个部门

​ 用户自定义完整性–例如用户名唯一,密码不能为空等

​ 3.2.2、约束的分类:

​ 键约束:主键约束、外键约束、唯一键约束

​ Not NULL约束:非空约束

​ Check约束:检查约束

​ Default约束:默认值约束

​ 自增约束

​ 3.2.3、约束与索引

​ 约束是用来对数据业务规则与数据完整性进行实施、维护,约束的作用范围仅限在当前数据库,约束可以被当做数据库对象来处理(逻辑概念,不占用内存

​ 索引是一个单独的、物理的存储在数据页上的数据结构,是表中一列或者若干列值的集合和对应的只想表中数据值的物理标识的数据页的逻辑指针清单,索引的存在会增加数据库的存储空间,目的是提高查询速度,但是会增大插入、修改数据的开销

​ MySQL会在主键、唯一键、外键列上自动创建索引,其他列则需要手动创建

3.3、主键约束-primary key

​ 1)唯一且非空

​ 2)一个表只能有一个主键约束

​ 3)主键约束名就叫做PRIMARY

​ 4)创建主键会自动创建相应的索引,同样删除主键相应的索引也会被删除

建表前定义主键约束
mysql>  create table test02.t_stu(
    ->  sid int primary key,
    ->  sname varchar(20),
    ->  gender char);
Query OK, 0 rows affected (0.03 sec)

mysql> desc t_stu;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sid    | int(11)     | NO   | PRI | NULL    |       |
| sname  | varchar(20) | YES  |     | NULL    |       |
| gender | char(1)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

​ 测试主键:

mysql>  insert into t_stu values(1, '张三', '男')->  (1, '李四', '女');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',
 (1, '李四', '')' at line 1
 
 正确案例:
 mysql>  insert into t_stu values(1, '张三', '男'),(2, '李四', '女');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from t_stu;
+-----+-------+--------+
| sid | sname | gender |
+-----+-------+--------+
|   1 | 张三  ||
|   2 | 李四  ||
+-----+-------+--------+
2 rows in set (0.00 sec)
建表后定义主键约束
mysql> create table test02.t_stu(
    ->  sid int,
    ->  sname varchar(20),
    ->  gender char);
Query OK, 0 rows affected (0.03 sec)

mysql> desc t_stu;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sid    | int(11)     | YES  |     | NULL    |       |
| sname  | varchar(20) | YES  |     | NULL    |       |
| gender | char(1)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table test02.t_stu add primary key(sid);
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc t_stu;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sid    | int(11)     | NO   | PRI | NULL    |       |
| sname  | varchar(20) | YES  |     | NULL    |       |
| gender | char(1)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

–单列主键约束:如上面所述,主键只有一个属性

–复合主键约束–两个或者多个属性作为主键

mysql>  create table test02.t_course(
    ->  cid int,
    ->  cname varchar(20));
Query OK, 0 rows affected (0.03 sec)
mysql>  create table test02.xuanke(
    ->  cid int,
    ->  sid int,
    ->  score int,
    ->  primary key(sid, cid));
Query OK, 0 rows affected (0.03 sec)

mysql> desc xuanke;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| cid   | int(11) | NO   | PRI | NULL    |       |
| sid   | int(11) | NO   | PRI | NULL    |       |
| score | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

建表后再确定复合主键与上面一样

删除主键约束
alter table [数据库名.]表名称 drop primary key;

mysql> desc t_stu;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sid    | int(11)     | NO   | PRI | NULL    |       |
| sname  | varchar(20) | YES  |     | NULL    |       |
| gender | char(1)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table t_stu drop primary key;
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc t_stu;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sid    | int(11)     | NO   |     | NULL    |       |
| sname  | varchar(20) | YES  |     | NULL    |       |
| gender | char(1)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
3.4、唯一键约束

​ 1)一个表可以有多个唯一键约束

​ 2)唯一键可以为null

​ 3)唯一键的约束名可以自己指定或者默认(如果单列唯一则是列明,如果是多列组合则是第一列的名称)

​ 4)创建唯一键约束也会在对应列上建立索引,删除唯一键约束的方法是通过删除唯一键的索引实现

3.4.1、建立唯一键约束

​ 同样分为单列唯一键与复合唯一键

mysql> create table books(
    -> bid int primary key,
    -> bname varchar(20) unique key,
    -> price double);
Query OK, 0 rows affected (0.03 sec)

mysql> desc books;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| bid   | int(11)     | NO   | PRI | NULL    |       |
| bname | varchar(20) | YES  | UNI | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> create table pen(
    -> pid int primary key,
    -> pname varchar(20),
    -> price double,
    -> unique key(pname, price));
Query OK, 0 rows affected (0.03 sec)

mysql> desc pen;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| pid   | int(11)     | NO   | PRI | NULL    |       |
| pname | varchar(20) | YES  | MUL | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

建完表后定义唯一键

mysql> desc books;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| bid   | int(11)     | NO   | PRI | NULL    |       |
| bname | varchar(20) | YES  |     | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table test02.books add unique key(bname, price);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc books;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| bid   | int(11)     | NO   | PRI | NULL    |       |
| bname | varchar(20) | YES  | MUL | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
3.4.2、查看索引
mysql> show index from text02.books;
ERROR 1049 (42000): Unknown database 'text02'
mysql> show index from test02.books;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| books |          0 | PRIMARY  |            1 | bid         | A         |           0 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| books |          0 | bname    |            1 | bname       | A         |           0 |     NULL |   NULL | YES  | BTREE      |         |               | YES     | NULL       |
| books |          0 | bname    |            2 | price       | A         |           0 |     NULL |   NULL | YES  | BTREE      |         |               | YES     | NULL       |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
3 rows in set (0.01 sec)

​ 3.4.3、删除唯一键约束–就是删除索引

mysql> desc books;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| bid   | int(11)     | NO   | PRI | NULL    |       |
| bname | varchar(20) | YES  | MUL | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table books drop index bname;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc books;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| bid   | int(11)     | NO   | PRI | NULL    |       |
| bname | varchar(20) | YES  |     | NULL    |       |
| price | double      | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
3.5、非空约束
3.5.1、特点:

​ 1)一个表可以有很多个非空约束

​ 2)非空约束智能针对某一个字段来说

​ 3)非空约束意味着,字段不能存入null值

3.5.2、创建非空约束 (建表时确定)
create table 表名(
字段名 字段属性 primary key,#主键约束
字段名 字段属性 not null,#非空约束
);
例如:
create table pencil(
	pid int(10) primary key,
	pname varchar(20) unique key not null,
	price double not null);
	mysql> create table pencil(
    -> pid int(10) primary key,
    -> pname varchar(20) unique key not null,
    -> price double not null);
Query OK, 0 rows affected, 1 warning (0.04 sec)

mysql> desc pencil
    -> ;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| pid   | int(10)     | NO   | PRI | NULL    |       |
| pname | varchar(20) | NO   | UNI | NULL    |       |
| price | double      | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> insert into pencil values(1, 'chenguang', null);
ERROR 1048 (23000): Column 'price' cannot be null
mysql> insert into pencil values(1, 'chenguang', 1.0);
Query OK, 1 row affected (0.01 sec)

mysql> select * from pencil;
+-----+-----------+-------+
| pid | pname     | price |
+-----+-----------+-------+
|   1 | chenguang |     1 |
+-----+-----------+-------+
1 row in set (0.00 sec)
3.5.3、建完表后指定非空约束

alter table 表明 modify 字段名 数据类型 not null;

mysql> desc pencil;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| pid    | int(10)     | NO   | PRI | NULL    |       |
| pname  | varchar(20) | NO   | UNI | NULL    |       |
| price  | double      | NO   |     | NULL    |       |
| number | int(3)      | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> update pencil set number = 5;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> alter table pencil modify number int(3) not null;
Query OK, 0 rows affected, 1 warning (0.17 sec)
Records: 0  Duplicates: 0  Warnings: 1

mysql> desc pencil;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| pid    | int(10)     | NO   | PRI | NULL    |       |
| pname  | varchar(20) | NO   | UNI | NULL    |       |
| price  | double      | NO   |     | NULL    |       |
| number | int(3)      | NO   |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

注意:在设定非空约束时应保证整个表中该属性非空

3.5.4 删除非空约束
alter table 表明 modify 字段名 数据类型 not null;

mysql> desc pencil;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| pid    | int(10)     | NO   | PRI | NULL    |       |
| pname  | varchar(20) | NO   | UNI | NULL    |       |
| price  | double      | NO   |     | NULL    |       |
| number | int(3)      | NO   |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> alter table pencil modify number int(3);
Query OK, 0 rows affected, 1 warning (0.18 sec)
Records: 0  Duplicates: 0  Warnings: 1

mysql> desc pencil
    -> ;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| pid    | int(10)     | NO   | PRI | NULL    |       |
| pname  | varchar(20) | NO   | UNI | NULL    |       |
| price  | double      | NO   |     | NULL    |       |
| number | int(3)      | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
3.6、默认值约束
3.6.1、特点

​ 1)一个表可以有很多个默认值约束

​ 2)智能针对某一个字段

​ 3)意味着该字段没有进行赋值则会按照默认值进行处理

3.6.2、创建默认值约束
create table 表名(字段 数据类型 约束 default 默认值); 

mysql> desc t_pen;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| pid   | int(2)      | NO   | PRI | NULL    |       |
| sname | varchar(20) | NO   |     | NULL    |       |
| price | double      | YES  |     | 1       |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> select * from t_pen;
Empty set (0.00 sec)
mysql> insert into t_pen values(1, '晨光', 3.5);
Query OK, 1 row affected (0.01 sec)

mysql> insert into t_pen values(2, '真彩', default);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t_pen;
+-----+-------+-------+
| pid | sname | price |
+-----+-------+-------+
|   1 | 晨光  |   3.5 |
|   2 | 真彩  |     1 |
+-----+-------+-------+
2 rows in set (0.00 sec)

mysql> insert into t_pen(pid, sname) values(3, '其他');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_pen;
+-----+-------+-------+
| pid | sname | price |
+-----+-------+-------+
|   1 | 晨光  |   3.5 |
|   2 | 真彩  |     1 |
|   3 | 其他  |     1 |
+-----+-------+-------+
3 rows in set (0.00 sec)
3.6.3、建表后定义默认值
alter table 表名 modify 字段名 数据类型 default 默认值

mysql> desc t_pen;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| pid   | int(2)      | NO   | PRI | NULL    |       |
| pname | varchar(20) | YES  |     | NULL    |       |
| price | double      | YES  |     | 1       |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> alter table t_pen change sname pname varchar(20);
Query OK, 0 rows affected (0.17 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc t_pen;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| pid   | int(2)      | NO   | PRI | NULL    |       |
| pname | varchar(20) | YES  |     | NULL    |       |
| price | double      | YES  |     | 1       |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> insert into t_pen values(5, default, default);
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_pen;
+-----+----------+-------+
| pid | pname    | price |
+-----+----------+-------+
|   1 | 晨光     |   3.5 |
|   2 | 真彩     |     1 |
|   3 | 其他     |     1 |
|   5 | 其它品牌 |     1 |
+-----+----------+-------+
4 rows in set (0.00 sec)
3.7、检查约束(check)mysql不支持
#检查约束
 create table t_stu(
 	sid int primary,
 	sname varchar(20),
 	gender char check('男' or '女'));#即只能添加男或者女
3.8、自增约束
3.8.1、特点

​ 1)一个表只能有一个自增约束-因为一个表只有一个维护自增至的变量

​ 2)自增约束的列只能是整数列

​ 3)自增约束的列必然是键列(主键、唯一键,外键)

3.8.2、建表时指定自增约束

​ 自增列:如果指定值,就按照指定的来,如果没有指定值就自增

​ 如果指定的值是0/null,就按照自增的来.

 create table 表明(
 	字段名 int primary key auto_increment,
 	字段名 数据类型);
 	
mysql>  create table t_stu2(
    ->  sid int primary key auto_increment,
    ->  sname varchar(20));
Query OK, 0 rows affected (0.03 sec)

mysql> desc t_stu2;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| sid   | int(11)     | NO   | PRI | NULL    | auto_increment |
| sname | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> insert into t_stu2(sname) values('张三');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_stu2;
+-----+-------+
| sid | sname |
+-----+-------+
|   1 | 张三  |
+-----+-------+
1 row in set (0.00 sec)

mysql> insert into t_stu2(sname) values('李四');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_stu2;
+-----+-------+
| sid | sname |
+-----+-------+
|   1 | 张三  |
|   2 | 李四  |
+-----+-------+
2 rows in set (0.00 sec)

mysql> insert into t_stu2 values(5, '李四');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_stu2;
+-----+-------+
| sid | sname |
+-----+-------+
|   1 | 张三  |
|   2 | 李四  |
|   5 | 李四  |
+-----+-------+
3 rows in set (0.00 sec)

mysql> insert into t_stu2(sname) values('wangwu');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_stu2;
+-----+--------+
| sid | sname  |
+-----+--------+
|   1 | 张三   |
|   2 | 李四   |
|   5 | 李四   |
|   6 | wangwu |
+-----+--------+
4 rows in set (0.00 sec)

alter table 表明 modify 字段名 数据类型 auto_increament;
3.8.3、取消自增
alter table 表明 modify 字段名 数据类型;
3.9、外键约束
3.9.1、特点:

​ 1)一个表可以有很多个外键约束

​ 2)外键约束是需要一个表的两个字段或者两个表的两个字段之间建立外键约束

​ 3)外键约束一定是在从表/子表中建立

​ 主表、子表:参考别人的,以来别人的

​ 从表、父表:被参考的,被依赖的

​ 4)在从表中外键约束的列,与在主表中外键约束参考的列,这两个列名称可以不一样,但是意义、数据类型必须一致

​ 5)外键约束是约束双方行为的

​ 对于主表来说:修改与删除受限制

​ 对于从表来说:添加与修改被限制

​ 6)主表被参考的列必须为主键列

​ 举例:部门表与员工表,员工的部门必须在部门表中有体现,那么部门表修改与删除的部门不能存在于员工表中,员工表修改与添加的部门必须在部门表中

建表时先建立主表,再建立从表

删表时先删除从表,再删除主表

3.9.2、约束等级(5个)

​ 1)Cascade方式:级联

​ 主动权在主表上,如果主表被依赖字段修改了,从表对应的外键字段跟着修改

​ 2)Set null方式

​ 主动权在主表上,如果主表被依赖字段修改或者删除了,那么修改为null

​ 3)No action方式:不作为模式

​ 4)Restrict方式:严格

​ 如果主表的被依赖字段的值被引用了,那么主表对该字段的修改和删除就被限制了

​ 5)set default方式:mysql 的Innodb引擎不支持

3.9.3、在建表时指定外键
mysql> create database 0513db;
Query OK, 1 row affected (0.01 sec)

mysql> use 0513db;
Database changed
mysql> #主表
mysql> create table dept(
    -> did int primary key,
    -> dname varchar(20));
Query OK, 0 rows affected (0.03 sec)

mysql> #从表
mysql> create table emp(
    -> eid int primary key,
    -> ename varchar(20),
    -> did int,
    -> foreign key(did) references dept(did) on update cascade on delete set null);
Query OK, 0 rows affected (0.03 sec)

mysql> desc dept;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| did   | int(11)     | NO   | PRI | NULL    |       |
| dname | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> desc emp;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| eid   | int(11)     | NO   | PRI | NULL    |       |
| ename | varchar(20) | YES  |     | NULL    |       |
| did   | int(11)     | YES  | MUL | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> insert into dept values(1, '咨询部'),
    -> (2, '外联部');
    
    mysql> select * from dept;
+-----+--------+
| did | dname  |
+-----+--------+
|   1 | 咨询部 |
|   2 | 生产部 |
+-----+--------+
2 rows in set (0.00 sec)

insert into emp values(2, '李四', 1);
Query OK, 1 row affected (0.01 sec)
mysql> select * from emp;
+-----+-------+------+
| eid | ename | did  |
+-----+-------+------+
|   1 | 张三  |    1 |
|   2 | 李四  |    1 |
+-----+-------+------+
2 rows in set (0.00 sec)

mysql> insert into emp values(3, '王五', 3);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`0513db`.`emp`, CONSTRAINT `emp_ibfk_1` FOREIGN KEY (`did`) REFERENCES `dept` (`did`) ON DELETE SET NULL ON UPDATE CASCADE)

mysql> delete from emp where did = 1;
Query OK, 2 rows affected (0.01 sec)

#删除从表中的数据
mysql> select * from emp;
+-----+-------+------+
| eid | ename | did  |
+-----+-------+------+
|   3 | 王五  |    2 |
+-----+-------+------+
1 row in set (0.00 sec) 

#级联约束,修改主表元素,从表也改变
mysql> select * from emp;
+-----+-------+------+
| eid | ename | did  |
+-----+-------+------+
|   3 | 王五  |    2 |
+-----+-------+------+
1 row in set (0.00 sec)

mysql> update dept set did = 5 where did = 2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from emp;;
+-----+-------+------+
| eid | ename | did  |
+-----+-------+------+
|   3 | 王五  |    5 |
+-----+-------+------+
1 row in set (0.00 sec)
3.9.4、建表后指定外键
alter table 从表名称 add foreign key(从表字段) references 主表名(主表字段) on update cascade on delete set null);
3.9.5、删除外键
alter table 从表名称 drop foreign key 约束名;
#约束名是随机生成的,记录在 information_schema中
#查看约束的指令为:
select * from  information_schema.table_constraints where table_name = '表名称'

mysql> select * from information_schema.table_constraints where table_name = 'emp';
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
| CONSTRAINT_CATALOG | CONSTRAINT_SCHEMA | CONSTRAINT_NAME | TABLE_SCHEMA | TABLE_NAME | CONSTRAINT_TYPE | ENFORCED |
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
| def                | 0513db            | PRIMARY         | 0513db       | emp        | PRIMARY KEY     | YES      |
| def                | 0513db            | emp_ibfk_1      | 0513db       | emp        | FOREIGN KEY     | YES      |
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
2 rows in set (0.01 sec)

#删除操作
mysql> alter table emp drop foreign key emp_ibfk_1;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0
mysql> select * from information_schema.table_constraints where table_name = 'emp';
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
| CONSTRAINT_CATALOG | CONSTRAINT_SCHEMA | CONSTRAINT_NAME | TABLE_SCHEMA | TABLE_NAME | CONSTRAINT_TYPE | ENFORCED |
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
| def                | 0513db            | PRIMARY         | 0513db       | emp        | PRIMARY KEY     | YES      |
+--------------------+-------------------+-----------------+--------------+------------+-----------------+----------+
1 row in set (0.00 sec)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章