Mysql添加外键约束.

最近学习遇到一条添加外键约束的语句,记录下来.

alter table selection add constraint FK_Reference_1 foreign key(course) references course (id) on delete restrict on update restrict;
alter table selection add constraint FK_Reference_2 foreign key(student) references student (id) on delete restrict on update restrict;

InnoDB中外键约束定义的语法如下:

ALTER TABLE tbl_name
    ADD [CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

 

转自:https://www.cnblogs.com/ALXPS/p/8016429.html

CASCADE
在父表上update/delete记录时,同步update/delete掉子表的匹配记录 

SET NULL
在父表上update/delete记录时,将子表上匹配记录的列设为null (要注意子表的外键列不能为not null)  

NO ACTION
如果子表中有匹配的记录,则不允许对父表对应候选键进行update/delete操作  

RESTRICT
同no action, 都是立即检查外键约束

SET NULL
父表有变更时,子表将外键列设置成一个默认的值 但Innodb不能识别

 

NULL、RESTRICT、NO ACTION
删除:从表记录不存在时,主表才可以删除。删除从表,主表不变
更新:从表记录不存在时,主表才可以更新。更新从表,主表不变
 
CASCADE
删除:删除主表时自动删除从表。删除从表,主表不变
更新:更新主表时自动更新从表。更新从表,主表不变
 
SET NULL
删除:删除主表时自动更新从表值为NULL。删除从表,主表不变
更新:更新主表时自动更新从表值为NULL。更新从表,主表不变
posted @ 2019-09-19 17:04  Umbrellaox  阅读(4956)  评论(0编辑  收藏  举报