Mysql新增外來鍵約束

2022-08-17 14:21:16 字數 1392 閱讀 1981

最近學習遇到一條新增外來鍵約束的語句,記錄下來.

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不能識別

null、restrict、no action

刪除:從表記錄不存在時,主表才可以刪除。刪除從表,主表不變

更新:從表記錄不存在時,主表才可以更新。更新從表,主表不變

cascade

刪除:刪除主表時自動刪除從表。刪除從表,主表不變

更新:更新主表時自動更新從表。更新從表,主表不變

set null

刪除:刪除主表時自動更新從表值為null。刪除從表,主表不變

更新:更新主表時自動更新從表值為null。更新從表,主表不變

Mysql 為表新增外來鍵約束

sql語句格式 新增外來鍵約束 alter table 從表 add constraint 外來鍵 形如 fk 從表 主表 foreign key 從表外來鍵字段 references 主表 主鍵字段 如果mysql報錯 error code 1215.cannot add foreign key ...

mysql中新增外來鍵約束失敗

mysql中新增外來鍵約束遇到一下情況 cannot add foreign key constraint 出現這個問題一般是開發工作者對外鍵的使用出現了疏忽,我們先清晰一下外來鍵的使用 1.外來鍵字段不能為該錶的主鍵 2.外來鍵字段參考字段必須為參考表的主鍵。如果出現 cannot add for...

mysql約束與外來鍵 MySQL 外來鍵與約束

外來鍵的建立 建表如下 create table parent id int not null,primary key id type innodb create table child id int,parent id int,foreign key parent id references pa...