MySQL表的约束
真正约束字段的是数据类型,但是数据类型约束很单一,需要有一些额外的约束,更好的保证数据的合法性,从业务逻辑角度保证数据的正确性。比如有一个字段是email,要求是唯一的。
表的约束很多,这里主要介绍如下几个: null/not null
,default
,comment
,zerofill
,primary key
,auto_increment
,unique key
。
1. null
两个值:null(默认的)和not null(不为空)
数据库默认字段基本都是字段为空,但是实际开发时,尽可能保证字段不为空,因为数据为空没办法参与运算。
案例:
创建一个班级表,包含班级名,班级所在的教室和其他信息。
- 如果班级没有名字,你不知道你在哪个班级
- 如果教室没有名字,就不知道在哪上课
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.12 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)
mysql> insert into myclass (class_name, class_room, other) values ('高三2班', '101教室', '普通班');
Query OK, 1 row affected (0.01 sec)
mysql> select * from myclass;
+------------+------------+-----------+
| class_name | class_room | other |
+------------+------------+-----------+
| 高三2班 | 101教室 | 普通班 |
+------------+------------+-----------+
1 row in set (0.00 sec)
mysql> insert into myclass (class_name, class_room, other) values ('高三3班', '103教室');
ERROR 1136 (21S01): Column count doesn't match value count at row 1
mysql> insert into myclass (class_name, class_room) values ('高三3班', '103教室');
Query OK, 1 row affected (0.00 sec)
mysql> select * from myclass;
+------------+------------+-----------+
| class_name | class_room | other |
+------------+------------+-----------+
| 高三2班 | 101教室 | 普通班 |
| 高三3班 | 103教室 | NULL |
+------------+------------+-----------+
2 rows in set (0.00 sec)
所以我们在设计数据库表的时候,一定要在表中进行限制,满足上面条件的数据就不能插入到表中。这就是“约束”。
2. default
默认值:某一种数据会经常性的出现某个具体的值,可以在一开始就指定好,在需要真实数据的时候,用户可以选择性的使用默认值。
mysql> create table if not exists t1(
-> name varchar(20) not null,
-> age tinyint unsigned default 18,
-> gender char(2) default '男'
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> desc t1;
+--------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------------------+------+-----+---------+-------+
| name | varchar(20) | NO | | NULL | |
| age | tinyint(3) unsigned | YES | | 18 | |
| gender | char(2) | YES | | 男 | |
+--------+---------------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
默认值的生效:数据在插入的时候不给该字段赋值,就使用默认值。
mysql> insert into t1 (name,age,gender) values ('张三', 20, '女');
Query OK, 1 row affected (0.00 sec)
mysql> insert into t1 (name) values ('李四');
Query OK, 1 row affected (0.00 sec)
mysql> select * from t1;
+--------+------+--------+
| name | age | gender |
+--------+------+--------+
| 张三 | 20 | 女 |
| 李四 | 18 | 男 |
+--------+------+--------+
2 rows in set (0.01 sec)
3. comment
列描述:comment,没有实际含义,专门用来描述字段,会根据表创建语句保存,用来给程序员或DBA来进行了解。
mysql> create table if not exists t2(
-> name varchar(20) not null comment '用户名',
-> age tinyint unsigned default 18 comment '年龄',
-> gender char(1) default '男' comment '性别'
-> );
Query OK, 0 rows affected (0.01 sec)
通过desc查看不到注释信息:
mysql> desc t2;
+--------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------------------+------+-----+---------+-------+
| name | varchar(20) | NO | | NULL | |
| age | tinyint(3) unsigned | YES | | 18 | |
| gender | char(1) | YES | | 男 | |
+--------+---------------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
通过show可以看到:
mysql> show create table t2 \G
*************************** 1. row ***************************
Table: t2
Create Table: CREATE TABLE `t2` (
`name` varchar(20) NOT NULL COMMENT '用户名',
`age` tinyint(3) unsigned DEFAULT '18' COMMENT '年龄',
`gender` char(1) DEFAULT '男' COMMENT '性别'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
4. zerofill
刚开始学习数据库时,很多人对数字类型后面的长度很迷茫。通过show看看t3表的建表语句:
mysql> create table if not exists t3(
-> a int unsigned not null,
-> b int unsigned not null
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> desc t3;
+-------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| a | int(10) unsigned | NO | | NULL | |
| b | int(10) unsigned | NO | | NULL | |
+-------+------------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> show create table t3 \G
*************************** 1. row ***************************
Table: t3
Create Table: CREATE TABLE `t3` (
`a` int(10) unsigned NOT NULL,
`b` int(10) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
可以看到int(10),这个代表什么意思呢?整型不是4字节码?这个10又代表什么呢?其实没有zerofill这个属性,括号内的数字是毫无意义的。a和b列就是前面插入的数据,如下:
mysql> insert into t3 (a,b) values (1,2);
Query OK, 1 row affected (0.00 sec)
mysql> select * from t3;
+---+---+
| a | b |
+---+---+
| 1 | 2 |
+---+---+
1 row in set (0.00 sec)
但是对列添加了zerofill属性后,显示的结果就有所不同了。修改t3表的属性:
mysql> alter table t3 modify b int unsigned zerofill not null;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> select * from t3;
+---+------------+
| a | b |
+---+------------+
| 1 | 0000000002 |
+---+------------+
1 row in set (0.00 sec)
这次可以看到b的值由原来的2变成0000000002,这就是zerofill属性的作用,如果宽度小于设定的宽度(这里默认设置的是10),自动填充0。要注意的是,这只是最后显示的结果,在MySQL中实际存储的还是2。0000000002只是设置了zerofill属性后的一种格式化输出而已。
5. primary key
主键:primary key用来唯一的约束该字段里面的数据,不能重复,不能为空,一张表中最多只能有一个主键;主键所在的列通常是整数类型。
案例:
-
创建表的时候直接在字段上指定主键
mysql> create table if not exists test_key( -> id int unsigned primary key comment '学号', -> name varchar(20)not null -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc test_key; +-------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+------------------+------+-----+---------+-------+ | id | int(10) unsigned | NO | PRI | NULL | | | name | varchar(20) | NO | | NULL | | +-------+------------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)
-
主键约束:主键对应的字段中不能重复,一旦重复,操作失败。
mysql> insert into test_key values (1, '刘备'); Query OK, 1 row affected (0.01 sec) mysql> insert into test_key values (1, '张飞'); ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
-
删除主键
mysql> alter table test_key drop primary key; Query OK, 2 rows affected (0.03 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> desc test_key; +-------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+------------------+------+-----+---------+-------+ | id | int(10) unsigned | NO | | NULL | | | name | varchar(20) | NO | | NULL | | +-------+------------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)
-
当表创建好以后但是没有主键的时候,可以再次追加主键
mysql> alter table test_key add primary key(id); Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> desc test_key; +-------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+------------------+------+-----+---------+-------+ | id | int(10) unsigned | NO | PRI | NULL | | | name | varchar(20) | NO | | NULL | | +-------+------------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)
-
复合主键
在创建表的时候,在所有字段之后,使用primary key(主键字段列表)来创建主键,如果有多个字段作为主键,可以使用复合主键。mysql> create table if not exists t4( -> id int unsigned, -> course_id int unsigned comment '课程代码', -> score tinyint unsigned comment '分数', -> primary key(id, course_id) -> ); Query OK, 0 rows affected (0.01 sec) mysql> desc t4; +-----------+---------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+---------------------+------+-----+---------+-------+ | id | int(10) unsigned | NO | PRI | NULL | | | course_id | int(10) unsigned | NO | PRI | NULL | | | score | tinyint(3) unsigned | YES | | NULL | | +-----------+---------------------+------+-----+---------+-------+ 3 rows in set (0.00 sec) mysql> insert into t4 values(1,1234,90); Query OK, 1 row affected (0.00 sec) mysql> insert into t4 values(1,1267,80); Query OK, 1 row affected (0.00 sec) mysql> insert into t4 values(2,1234,70); Query OK, 1 row affected (0.00 sec) mysql> insert into t4 values(2,1234,70); ERROR 1062 (23000): Duplicate entry '2-1234' for key 'PRIMARY' mysql> select * from t4; +----+-----------+-------+ | id | course_id | score | +----+-----------+-------+ | 1 | 1234 | 90 | | 1 | 1267 | 80 | | 2 | 1234 | 70 | +----+-----------+-------+ 3 rows in set (0.00 sec)
6. auto_increment
auto_increment:当对应的字段,不给值,会自动的被系统触发,系统会从当前字段中已经有的最大值+1操作,得到一个新的不同的值。通常和主键搭配使用,作为逻辑主键。
自增长的特点:
- 任何一个字段要做自增长,前提是本身是一个索引(key一栏有值)
- 自增长字段必须是整数
- 一张表最多只能有一个自增长
mysql> create table if not exists t5(
-> id int unsigned primary key auto_increment,
-> name varchar(20) not null
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> insert into t5 (name) values ('a');
Query OK, 1 row affected (0.00 sec)
mysql> insert into t5 (name) values ('b');
Query OK, 1 row affected (0.01 sec)
mysql> insert into t5 (name) values ('c');
Query OK, 1 row affected (0.00 sec)
mysql> select * from t5;
+----+------+
| id | name |
+----+------+
| 1 | a |
| 2 | b |
| 3 | c |
+----+------+
3 rows in set (0.00 sec)
7. unique key
一张表中有往往有很多字段需要唯一性,数据不能重复,但是一张表中只能有一个主键:唯一键就可以解决表中有多个字段需要唯一性约束的问题。
唯一键的本质和主键差不多,唯一键允许为空,而且可以多个为空,空字段不做唯一性比较。
关于唯一键和主键的区别:
我们可以简单理解成,主键更多的是标识唯一性的。而唯一键更多的是保证在业务上,不要和别的信息出现重复。乍一听好像没啥区别,我们举一个例子:
比如在公司,我们需要一个员工管理系统,系统中有一个员工表,员工表中有两列信息,一个身份证号码,一个是员工工号,我们可以选择身份号码作为主键。
而我们设计员工工号的时候,需要一种约束:而所有的员工工号都不能重复。
具体指的是在公司的业务上不能重复,我们设计表的时候,需要这个约束,那么就可以将员工工号设计成为唯一键。
一般而言,我们建议将主键设计成为和当前业务无关的字段,这样,当业务调整的时候,我们可以尽量不会对主键做过大的调整。
mysql> create table student (
-> id char(10) unique comment '学号,不能重复,但可以为空',
-> name varchar(10)
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> insert into student(id, name) values('01', 'aaa');
Query OK, 1 row affected (0.00 sec)
mysql> insert into student(id, name) values('01', 'bbb'); --唯一约束不能重复
ERROR 1062 (23000): Duplicate entry '01' for key 'id'
mysql> insert into student(id, name) values(null, 'bbb'); -- 但可以为空
Query OK, 1 row affected (0.00 sec)
mysql> select * from student;
+------+------+
| id | name |
+------+------+
| 01 | aaa |
| NULL | bbb |
+------+------+
8. 外键
外键用于定义主表和从表之间的关系:外键约束主要定义在从表上,主表则必须是有主键约束或unique约束。当定义外键后,要求外键列数据必须在主表的主键列存在或为null。
语法:
foreign key (字段名) references 主表(列)
对上面的示意图进行设计:
-
先创建主键表
create table myclass ( id int primary key, name varchar(30) not null comment'班级名' );
-
再创建从表
create table stu ( id int primary key, name varchar(30) not null comment '学生名', class_id int, foreign key (class_id) references myclass(id) );
-
正常插入数据
mysql> insert into myclass values(10, 'C++大牛班'),(20, 'java大神班'); Query OK, 2 rows affected (0.03 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> insert into stu values(100, '张三', 10),(101, '李四',20); Query OK, 2 rows affected (0.01 sec) Records: 2 Duplicates: 0 Warnings: 0
-
插入一个班级号为30的学生,因为没有这个班级,所以插入不成功
mysql> insert into stu values(102, 'wangwu',30); ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (mytest.stu, CONSTRAINT stu_ibfk_1 FOREIGN KEY (class_id) REFERENCES myclass (id))
-
插入班级id为null,比如来了一个学生,目前还没有分配班级
mysql> insert into stu values(102, 'wangwu', null);
-
如何理解外键约束
首先我们承认,这个世界是数据很多都是相关性的。理论上,上面的例子,我们不创建外键约束,就正常建立学生表,以及班级表,该有的字段我们都有。此时,在实际使用的时候,可能会出现什么问题?有没有可能插入的学生信息中有具体的班级,但是该班级却没有在班级表中?
因为此时两张表在业务上是有相关性的,但是在业务上没有建立约束关系,那么就可能出现问题。
解决方案就是通过外键完成的。建立外键的本质其实就是把相关性交给mysql去审核了,提前告诉mysql表之间的约束关系,那么当用户插入不符合业务逻辑的数据的时候,mysql不允许你插入。