概述
| 约束 |
描述 |
关键字 |
| 主键约束 |
主键是一行数据的唯一标识,要求非空且唯一 |
primary key |
| 外键约束 |
用来让两张表的数据之间建立连接,保证数据的一致性和完整性 |
foreign key |
| 自动增长 |
|
auto_increment |
外键约束
- 添加外键:
alter table 表名 add constraint 外键名称 foreign key(外键字段名)references 主表(主表列名);
alter table emp add constraint fk_emp_dept_id foreign key(dept_id) references dept(id);
- 删除外键:
alter table 表名 drop foreign key 外键名称;
alter table emp drop foreign key fk_emp_dept_id;
删除/更新行为
| 行为 |
说明 |
| no action |
不允许删除/更新(与restrict一致) |
| restrict |
不允许删除/更新(与no action一致) |
| cascade |
子表随父表删除/更新 |
| set null |
父表删除时,子表中该值为null(允许取null时) |
- alter table 表名 add constraint 外键名称 foreign key(外键字段名)references 主表(主表列名)on update cascade on delete cascade;
alter table emp add constraint fk_emp_dept_id foreign key(dept_id) references dept(id) on update cascade on delete cascade;