最近学习遇到一条添加外键约束的语句,记录下来.
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]
CASCADE
在父表上update/delete记录时,同步update/delete掉子表的匹配记录
SET NULL
在父表上update/delete记录时,将子表上匹配记录的列设为null (要注意子表的外键列不能为not null)
NO ACTION
如果子表中有匹配的记录,则不允许对父表对应候选键进行update/delete操作
RESTRICT
同no action, 都是立即检查外键约束
SET NULL
父表有变更时,子表将外键列设置成一个默认的值 但Innodb不能识别