约束
概述
概念
约束是作用于表中字段上的规则,用于限制存储在表中的数据
目的
保证数据库中数据的正确性、有效性、和完整性。
分类
| 约束 | 描述 | 关键字 |
|---|---|---|
| 非空约束 | 限制该字段的数据不能加null | not null |
| 唯一约束 | 保证该字段的所有数据都是唯一、不重复的 | unique |
| 主键约束 | 主键是一行数据的唯一标识,要求非空且唯一 | primary key |
| 默认约束 | 保存数据时,如果未指定该字段的值,则采用默认值 | default |
| 检查约束(8.0.16版本之后) | 保证字段值满足某一个条件 | check |
| 外键约束 | 用来让两张表的数据之间建立连接,保证数据的一致性和完整性 | foreign key |
注意:约束是作用于表中字段上的,可以在创建表的时候添加约束|
约束演示
案例:根据需求,完成表结构的创建
create table user(
id int primary key auto_increment comment '主键',
name varchar(10) not null unique comment '姓名',
age int check(age > 0 and age <= 120) comment '年龄',
status char(1) default '1' comment '状态',
gender char(1) commment '性别'
)comment '用户表';
外键约束
概念
外键用来让两张表的数据之间建立连接,从而保证数据的一致性和完整性。
语法
添加外键
create table 表名(
字段名 数据类型
...
[constraint][外键名称] foreign key(外键字段名) references 主表(主表列名)
);
alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主列表名)
举例:将emp表的id和dept表的id关联
alter table emp add constraint fk_emp_dept_id foreign key(dept_id) references dept(id);
删除外键
alter table 表名 drop foreign key 外键名称;
eg:alter table emp drop foreign key fk_emp_dept_id;
删除/更新行为
| 行为 | 说明 |
|---|---|
| no action | 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新。(与restrict一致) |
| restrict | 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新。(与no action一致) |
| cascade | 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有,则也删除/更新外键在子表中的记录 |
| set null | 当在父表中删除对应记录时,首先检查该记录是否有对应外键,如果有,则设置子表中该外键值为null(这就要求该外键允许取null)。 |
| set default | 父表有变更时,子表将外键列设置成一个默认的值(innodb不支持)。 |
- cascade
alter table 表名 add constraint 外键名称 foreign key (外键字段) references 主表名(主表字段名) on update cascade on delete cascade;
eg:alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade; - set null
alter table 表名 add constraint 外键名称 foreign key (外键字段) references 主表名(主表字段名) on update set null on delete set null;