06 - MySQL表的约束

表中的约束

表中一定要有约束, 通过约束, 让我们未来插入的数据库表中的数据是符合预期的 约束本质是通过技术手段, 倒逼我们的程序员插入正确的数据 反过来, 站在 mysql 的视角, 凡事插入进来的数据, 都是符合约束的

约束的最终目标: 保证数据的完整性和可预期性

非空约束

  • 空 NULL
  • 非空 NOT NULL

我们可以在建表的时候在列类型后面加上 not null 字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
mysql> create table myclass(
-> class_name varchar(20) not null,
-> class_room varchar(20) not null,
-> other varchar(20)
-> );
Query OK, 0 rows affected (0.02 sec)

mysql> desc myclass;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| class_name | varchar(20) | NO | | NULL | |
| class_room | varchar(20) | NO | | NULL | |
| other | varchar(20) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

这里的 class_name 和 class_room 加上了 not null 约束, 所以 desc 的 Null 属性是 No, 代表不能是空

1
2
3
4
5
6
7
8
9
mysql> show create table myclass\G
*************************** 1. row ***************************
Table: myclass
Create Table: CREATE TABLE `myclass` (
`class_name` varchar(20) NOT NULL,
`class_room` varchar(20) NOT NULL,
`other` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3
1 row in set (0.00 sec)

这里也能看出这个约束的区别

default 约束

默认值: 某一种数据会经常的出现某个具体的值, 可以在一开始就指定好, 在需要真实数据的时候, 用户可以选择性的使用默认值

1
2
3
4
5
6
mysql> create table t13(
-> name varchar(20) not null,
-> age tinyint unsigned default 18,
-> gender char(1) default 'M'
-> );
Query OK, 0 rows affected (0.02 sec)
1
2
3
4
5
6
7
8
9
mysql> desc t13;
+--------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | 18 | |
| gender | char(1) | YES | | M | |
+--------+------------------+------+-----+---------+-------+
3 rows in set (0.01 sec)
  • default 如果设置了, 如果用户有数据插入就用用户的, 如果没有就用 default
1
2
3
4
5
6
7
8
9
10
mysql> insert into t13 (name) values ('Sarzn');
Query OK, 1 row affected (0.00 sec)

mysql> select * from t13;
+-------+------+--------+
| name | age | gender |
+-------+------+--------+
| Sarzn | 18 | M |
+-------+------+--------+
1 row in set (0.00 sec)

再来看下面这个例子 我们创建一个这样的表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
mysql> create table t5(
-> name varchar(20) not null,
-> age tinyint default 18,
-> gender char(1) not null default 'M'
-> );
Query OK, 0 rows affected (0.02 sec)

mysql> desc t5;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| name | varchar(20) | NO | | NULL | |
| age | tinyint | YES | | 18 | |
| gender | char(1) | NO | | M | |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

我们尝试给 name 插入 null

1
2
3
4
mysql> insert into t5 (name, age, gender) values (null, 20,  'M');
ERROR 1048 (23000): Column 'name' cannot be null
mysql> insert into t5 (age, gender) values (20, 'M');
ERROR 1364 (HY000): Field 'name' doesn't have a default value

发现这两种插入都被拦截了, 但是报错的信息各不相同

  1. 在插入的时候指定 name 为 null 时候, 因为name 被指定了, 所以 default 会被忽略. 此时填入 null ,但是受到 not null 约束, 报错 cannot be null
  2. 在插入的时候省略 name 的时候, 默认使用 default, 但是此时 default 是没有默认值的, 所以报错 doesn’t have a default value

注意!

需要注意的是 desc 显示的 default 是 null 分为两种情况.

  1. 允许 null, “default 有值, 值是 null”
  2. not null, desc 的 default 虽然还是 null, 但是他是表示”没有值”的意思, 而不是”有值,值是 null “的意思

我们可以通过 show create table 看出来差别

1
2
3
4
5
6
7
8
9
10
mysql> show create table t5\G
*************************** 1. row ***************************
Table: t5
Create Table: CREATE TABLE `t5` (
`name` varchar(20) NOT NULL,
`age` tinyint DEFAULT '18',
`gender` char(1) NOT NULL DEFAULT 'M',
`number` char(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3
1 row in set (0.00 sec)

1
2
3
4
5
6
7
8
9
10
mysql> desc t5;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| name | varchar(20) | NO | | NULL | |
| age | tinyint | YES | | 18 | |
| gender | char(1) | NO | | M | |
| number | char(11) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

这里看 name 和 number 这里desc 的 default 都是 null 但是 show create table 却表明 name 是没有 default, number 的 default 是 null

这样我们就可以很好的解释下面的这个 gender 的例子了

1
2
3
4
5
6
7
8
9
10
11
12
mysql> insert into t5 (name, age, gender) values ('Sarzn', 20, null);
ERROR 1048 (23000): Column 'gender' cannot be null
mysql> insert into t5 (name, age) values ('Sarzn', 20);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t5;
+-------+------+--------+
| name | age | gender |
+-------+------+--------+
| Sarzn | 20 | M |
+-------+------+--------+
1 row in set (0.00 sec)

所以 default 和 not null 不冲突, 而是互相补充的 作用:

  • not null: 要求字段最终不能是 NULL
  • default: 决定省略字段或使用 DEFAULT 关键字时填什么值. 如果一旦被指定, 那么就用指定的值

这样你再回过头来看上面那个 not null 和 doesn’t have a default value 便清晰了

但是在实际数据库操作中, 我们的 default 和 not null 一般不会同时出现, 因为 default 了就会让这个字段 not null. 如果我们写了 not null default 的话那唯一的作用是让用户不能输 null

comment 约束

列描述

zerofill

代表: 显示数字时,不足指定宽度就在左边补 0, 如果宽度超过个就直接显示 这和 int(n) 这个 n 密不可分, 这里的 n 表示的是 int 显示的宽度

注意: 新版 mysql 已经弃用 zerofill 了, 但是你确实可以继续使用, 只不过会受到相关警告

1
2
3
4
5
6
7
8
mysql> show create table t6\G
*************************** 1. row ***************************
Table: t6
Create Table: CREATE TABLE `t6` (
`a` int unsigned NOT NULL,
`b` int(4) unsigned zerofill NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3
1 row in set (0.00 sec)
1
2
3
4
5
6
7
8
9
10
11
12
13
mysql> select * from t6;
+---+--------+
| a | b |
+---+--------+
| 1 | 0002 |
| 1 | 0001 |
| 1 | 0011 |
| 1 | 0111 |
| 1 | 1111 |
| 1 | 11111 |
| 1 | 111111 |
+---+--------+
7 rows in set (0.00 sec)

~如果 int 后面没有括号的话那么它默认是 int(11)~ 这句话是不正确的 如果 int unsigned 后面没有括号的话那么它默认是 int(10)

注意: 不存在有符号的 int zerofill. 因为 zerofill 会自动附带上 unsigned.

1
2
3
4
5
6
7
8
9
10
11
12
13
mysql> alter table t6 add c int zerofill;
Query OK, 0 rows affected, 1 warning (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 1

mysql> show create table t6\G
*************************** 1. row ***************************
Table: t6
Create Table: CREATE TABLE `t6` (
`a` int unsigned NOT NULL,
`b` int(4) unsigned zerofill NOT NULL,
`c` int(10) unsigned zerofill DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3
1 row in set (0.00 sec)

主键约束

主键: primary key 用来唯一的约束该字段里面的数据, 不能重复, 不能为空, 一张表中最多只能有一个主键; 主键所在的列通常是整数类型

设置了主键之后会被自动加上 not null 约束

如果主键冲突会发生错误

1
2
3
4
5
6
7
8
9
10
11
mysql> select * from test_key;
+----+-------+
| id | name |
+----+-------+
| 1 | Sarzn |
| 2 | Sarzn |
+----+-------+
2 rows in set (0.00 sec)

mysql> insert into test_key (id, name) values (2, 'Sarzn');
ERROR 1062 (23000): Duplicate entry '2' for key 'test_key.PRIMARY'

使用 alter table 表名 drop primary key; 可以删除主键设定

1
2
3
mysql> alter table test_key drop primary key;
Query OK, 2 rows affected (0.05 sec)
Records: 2 Duplicates: 0 Warnings: 0

使用 alter table 表名 add primary key(指定主键); 可以为当前表添加主键

1
2
3
mysql> alter table test_key add primary key(id);
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0
1
2
3
4
5
6
7
8
9
mysql> show create table test_key\G
*************************** 1. row ***************************
Table: test_key
Create Table: CREATE TABLE `test_key` (
`id` int unsigned NOT NULL,
`name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3
1 row in set (0.00 sec)

但是在给一个已经存在的表添加主键的时候要注意此时表中的主键不能出现重复,. 不让会出现如下报错

1
2
3
4
5
6
7
8
9
10
11
12
mysql> select * from test_key;
+----+-------+
| id | name |
+----+-------+
| 1 | Sarzn |
| 2 | Sarzn |
| 2 | Sarzn |
+----+-------+
3 rows in set (0.00 sec)

mysql> alter table test_key add primary key(id);
ERROR 1062 (23000): Duplicate entry '2' for key 'test_key.PRIMARY'

这时你就需要删除重复的主键才行

所以我们在数据库设计的时候尽量在一开始就设定好主键, 尽可能的避免出现后添加主键的情况

一个主键不仅仅可以被添加到一列上, 也可以多列都是主键, 他们共同组成复合主键, 即这两个合起来才是主键

auto_increment

自增, 即每次插入新值的时候, 被描述的列会自增 1 加上这个约束的值必须是主键, 否则会报错

使用 auto_increment 进行约束

1
2
3
4
5
mysql> create table t7(
-> id int unsigned primary key auto_increment,
-> name varchar(20) not null
-> );
Query OK, 0 rows affected (0.02 sec)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mysql> show create table t7\G
*************************** 1. row ***************************
Table: t7
Create Table: CREATE TABLE `t7` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3
1 row in set (0.00 sec)

mysql> desc t7;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

使用 insert into 插入时 auto_increment 主键自增

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mysql> insert into t7 (name) values ('a');
Query OK, 1 row affected (0.00 sec)

mysql> insert into t7 (name) values ('b');
Query OK, 1 row affected (0.01 sec)

mysql> insert into t7 (name) values ('c');
Query OK, 1 row affected (0.00 sec)

mysql> select * from t7;
+----+------+
| id | name |
+----+------+
| 1 | a |
| 2 | b |
| 3 | c |
+----+------+
3 rows in set (0.00 sec)

但是如果我直接指定插入 id 是 100 也能正常插入, 但是下次自增就是从 101 开始自增了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
mysql> insert into t7 (id, name) values (100, 'd');
Query OK, 1 row affected (0.00 sec)

mysql> select * from t7;
+-----+------+
| id | name |
+-----+------+
| 1 | a |
| 2 | b |
| 3 | c |
| 100 | d |
+-----+------+
4 rows in set (0.00 sec)

mysql> insert into t7 (name) values ('e');
Query OK, 1 row affected (0.00 sec)

mysql> select * from t7;
+-----+------+
| id | name |
+-----+------+
| 1 | a |
| 2 | b |
| 3 | c |
| 100 | d |
| 101 | e |
+-----+------+
5 rows in set (0.00 sec)

mysql 能做到从 100 开始的原因是在 show create table 能够看到一个 AUTO_INCREMNET 值, 他决定了我们下次自增出来是多少. 比如这里的 AUTO_INCREMENT 是 102 则说明下次自增的 id 是 102

1
2
3
4
5
6
7
8
9
mysql> show create table t7\G
*************************** 1. row ***************************
Table: t7
Create Table: CREATE TABLE `t7` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=102 DEFAULT CHARSET=utf8mb3
1 row in set (0.00 sec)

可以在表创建时就在表外设定自增长初始数值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mysql> create table t8(
-> id int unsigned primary key auto_increment,
-> name varchar(20)
-> )auto_increment=30;
Query OK, 0 rows affected (0.02 sec)

mysql> show create table t8\G
*************************** 1. row ***************************
Table: t8
Create Table: CREATE TABLE `t8` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8mb3
1 row in set (0.00 sec)

AUTO_INCREMNET 永远会是表中最大数值 + 1 的数, 如果你指定插入一个比 AUTO_INCREMENT 小的数值, 那么 AUTO_INCREMENT 不会被改变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
mysql> show create table t8\G
*************************** 1. row ***************************
Table: t8
Create Table: CREATE TABLE `t8` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=utf8mb3
1 row in set (0.00 sec)

mysql> insert into t8 (id, name) values(1, 'd');
Query OK, 1 row affected (0.00 sec)

mysql> show create table t8\G
*************************** 1. row ***************************
Table: t8
Create Table: CREATE TABLE `t8` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=utf8mb3
1 row in set (0.00 sec)

可以使用 last_insert_id() 来找到插入的最大的自增主键

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mysql> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
| 32 |
+------------------+
1 row in set (0.00 sec)

mysql> select * from t8;
+----+------+
| id | name |
+----+------+
| 1 | d |
| 30 | a |
| 31 | b |
| 32 | c |
+----+------+
4 rows in set (0.00 sec)

唯一键约束

一张表中往往有很多字段需要唯一性, 数据不能重复, 但是一张表中只能有一个主键: 唯一键就可以解决表中有很多个字段需要唯一性约束的问题

唯一键的本质和主键差不多, 但是唯一键允许为空, 而且可以多个为空, 空字段不做唯一性比较

唯一键和主键的区别 我们可以简单的理解成, 主键更多的是标识唯一性的. 而唯一键更多的是保证在业务上, 不要和别的信息出现重复

一般而言, 建议将主键设计为和当前业务无关的字段, 这样, 当业务调整的时候, 我们可以尽量不会对主键做过大的调整

使用 unique 约束来创建唯一键

1
2
3
4
5
6
mysql> create table stu(
-> id int primary key auto_increment,
-> name varchar(20),
-> phone char(20) unique
-> );
Query OK, 0 rows affected (0.02 sec)

如果对唯一键插入重复的值会报错

1
2
3
4
5
6
7
8
9
10
11
mysql> insert into stu(name, phone) values ('a', '123456787');
ERROR 1062 (23000): Duplicate entry '123456787' for key 'stu.phone'
mysql> select * from stu;
+----+------+-----------+
| id | name | phone |
+----+------+-----------+
| 1 | a | 123456789 |
| 2 | a | 123456788 |
| 3 | a | 123456787 |
+----+------+-----------+
3 rows in set (0.00 sec)

你可以对唯一键插入 NULL 值, NULL 值不进行唯一性检验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
mysql> insert into stu(name, phone) values ('a', null);
Query OK, 1 row affected (0.01 sec)

mysql> insert into stu(name, phone) values ('a', null);
Query OK, 1 row affected (0.01 sec)

mysql> insert into stu(name) values ('a');
Query OK, 1 row affected (0.01 sec)

mysql> select * from stu;
+----+------+-----------+
| id | name | phone |
+----+------+-----------+
| 1 | a | 123456789 |
| 2 | a | 123456788 |
| 3 | a | 123456787 |
| 5 | a | NULL |
| 6 | a | NULL |
| 7 | a | NULL |
+----+------+-----------+
6 rows in set (0.00 sec)

外键约束

外键用于定义主表和从表之间的关系: 外键约束主要定义在从表上, 主表则必须是有主键约束或者 unique 约束. 当定义外键之后, 要求外键列数据必须在主表的主键存在或者 null

先创建主表, 一定要有 primary key 或者是 unique

1
2
3
4
5
mysql> create table class(
-> id int primary key,
-> code varchar(20)
-> );
Query OK, 0 rows affected (0.02 sec)

再创建从表, 使用 foreign key(从表中的外键列) references 主表(主表的主键列)

1
2
3
4
5
6
7
mysql> create table student(
-> id int unsigned primary key,
-> name varchar(20) not null,
-> telphone varchar(20) unique,
-> class_id int,
-> foreign key(class_id) references class(id)
-> );

如果插入一个主表中不存在的外键会报错

1
2
mysql> insert into student values(3, 'c', '123456389', 3);
ERROR 1062 (23000): Duplicate entry '123456389' for key 'student.telphone'

这就很好的规避了我们出现不在任何已有班级中的学生

使用了外键我们就不会插入不在任何班级的学生, 和没有任何学生的班级了

给外键约束起名字

我们可以使用 constraint 给外键约束起名字, 如果你不指定名字的话 mysql 也会自己生成

1
2
3
4
5
6
7
mysql> create table student(
-> id int unsigned primary key,
-> name varchar(20) not null,
-> telphone varchar(20) unique,
-> class_id int,
-> constraint fk_student_class foreign key(class_id) references class(id)
-> );

通常我们使用 fk_子表名_父表名, 方便辨认

到时候如果我们想要删除这个外键约束也可以直接使用这个名字

1
ALTER TABLE student DROP FOREIGN KEY fk_student_class;