以学习数据库入门的学生表
与学院表
为例。
学生表以学号为主键,学院表以学院编号为主键。学生表中的学院编号参照学院表,作为学生表的外键。
现在的需求是:删除学院表中的学院,所属学院的学生在学生表中同时被删除。
-- 查看创建学生表的语句
SHOW create table tb_student;
-- 创建学生表语句
create table tb_student
(
stuid integer not null comment '学号',
stuname varchar(20) not null comment '姓名',
stusex boolean default 1 comment '性别',
stubirth date not null comment '出生日期',
stuaddr varchar(255) default '' comment '籍贯',
collid integer not null comment '所属学院',
primary key (stuid),
foreign key (collid) references tb_college (collid)
);
删除编号为1的学院
delete from `tb_college` where collid=1;
报错:
不能删除或者更新父行,因为有外键约束限制
学生表在建表的时候就创建了外键约束,mysql默认使用restrict
。
外键约束 | 含义 |
---|---|
restrict | 不能删除,不能更新(默认) |
cascade | 级连 |
set null | 设置为空 |
建表时创建的外键约束,被mysql自动命名。想要修改外键约束限制,得先知道外键的名字。
SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE table_name = 'tb_student';
mysql没有办法修改外键约束,只能删除重建。重建时设置外键约束的删除和更新操作。
-- 删除外键约束
alter table tb_student drop foreign key tb_student_ibfk_1;
-- 设置外键约束为级连删除
alter table tb_student add constraint fk_stu_collid foreign key (collid) references tb_college (collid) on delete cascade on update cascade;
-- 设置外键约束为删除级连更新为空
alter table tb_student add constraint fk_stu_collid foreign key (collid) references tb_college (collid) on delete set null on update cascade;