MySQL数据库外键

设置外键

外键及功能:成绩表(参照表也叫子表)中的学号来自学生表(被参照表也叫父表),成绩表中的课程号来自课程表;当要删除或更新被参照表中的给字段的值时,参照表该字段的值如何改变。在on delete on update设置参照动作:restrict(限制) cascade(级联)Set null(设置为空) no action(无动作)
简单点说就是外键所在的表是子表,外键所参照的表是父表。

A. restrict:当子表有相关记录时,禁止父表删除或更新此字段的值(默认);

B. cascade(级联):当父表记录删除或更新该字段的值时,子表跟着被删除或更新;

C. set null:如果子表该字段没设置为not null,当父表删除或更新时,子表相关记录的该字段的值设置为空;D. no action:与restrict一样。

使用命令创建外键Alter table cj add constraint cs_xh foreign key (学号) references xs(学号) on delete restrict on update cascade, add constraint cj_kch foreign key (课程号) references kc(课程号) on delete cascade on update cascada;
创建时设置外键Create table cj(学号 char(6) not null,课程号 char(3) not null,成绩 decimal(4,1),primary key(学号,课程号),Constraint cj_xh foreign key(学号) references xs(学号) on delete restrict on update cascade,constraint cj_kch foreign key (课程号) references kc(课程号) on delete cascade on update restrict);停止外键约束:set foreign_key_checks=0/off启用外键约束:set foreign_key_checks=1/on删除外键: alter table 表名drop foreign key 外键名;例:alter table cj drop foreign key cj_xh;查看外键是否打开:Show variables like “%foreign%”;

只为更好的服务;服务工作者。
原文地址:https://www.cnblogs.com/pony-mamba/p/13570808.html