一、约束
create table user(
id int primary key auto_increment comment "主键",
name varchar(10) not null unique comment "姓名",
age int check (age >0 && age <= 120) comment "年龄",
status char(1) default '1' comment "状态",
gender char(1) comment "性别",
) comment '用户表';
二、外键约束
外键用来让两张表的数据之间建立连接,从而保证数据的一致性和完整性。
注意:目前上述的两张表,在数据库里面,并未建立外键关联,即是当父表删除id=1的数据,子表数据没有改变,但是无法保证数据的一致性和完整性的。
添加外键
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references
dept(id);
删除外键
alter table emp drop foreign key fk_emp_dept_id;
三、外键约束删除更新行为
语法
建立外键约束并指定外键约束的删除和更新行为--CASCADE
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references
dept(id) on update cascade on delete cascade;-- 外键约束级联关系
从上图可以看出,当添加外键约束和删除与更新的行为时,父表id有修改,子表的外键也会同步更新。同理,若删除父表某条id记录后,子表对应的外键id记录也会被删除。
建立外键约束并指定外键约束的删除和更新行为--SET NULL
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references
dept(id) on update set null on delete set null;-- 外键约束级联关系