立即学习:https://edu.csdn.net/course/play/4364/77144?utm_source=blogtoedu
要求:
- 被引用表的列必须是主键、唯一、不为空、存储引擎innoDB(必须有索引,主键按照大小排序)
外键声明包括三个部分:
- 哪个列或列组合是外键
- 指定外键参照的表和列
- 参照动作【cascade(级联操作),restrict(拒绝操作),set null,no action,set default】
# 创建主表
create table student
(
sid int not null primary key,
sname varchar(20)
) engine=innodb
# 创建从表
create table score
(
sid int not null,
mark int,
constraint score_fk FOREIGN KEY (sid) reference student(sid) on delete cascade on update cascade
) engine=innodb
# 删除外键
alter table score drop foreign key score_fk
# 给现有表添加外键,动作修改为no action
alter table score add constraint score_fk foreith key(sid) references student(sid) on delete no action on update no action
# no action, 如果子表中有匹配的记录,则不允许对主表对应候选键进行update/delete 操作
update student set sid=11 where sid=10
delete from student where sid=10
# 除非先删除该学生的成绩,再删除该学生
delete from score where sid=10
**restrict 同no action
set null:
- 在父表上update/delete记录时,将子表上匹配的记录的列设为null。
- 注意:子表的外键列不能为not null。