mysql三种外键操作限制要求

[复制链接]
查看1806 | 回复0 | 2020-10-12 07:25 | 显示全部楼层 |阅读模式
mysql三种外键操作限制要求
1、  严格限制(参见主表和从表)
2、  置空操作(set null):如果主表记录删除,或关联字段更新,则从表外键字段被设置为null。
3、  级联操作(cascade):如果主表记录删除,则从表记录也被删除。主表更新,从表外键字段也更新。
语法:foreign key (外键字段) references 主表名 (关联字段) [主表记录删除时的动作] [主表记录更新时的动作]。
一般说删除时置空,更新时级联。
代码如下:
  1. drop table if exists stuinfo;
  2. create table stuinfo(
  3.        id tinyint primary key comment '学号,主键',
  4.        name varchar(20) comment '姓名'
  5. )engine=innodb;

  6. drop table if exists stuscore;
  7. create table stuscore(
  8.        id int auto_increment primary key comment '主键',
  9.        sid tinyint comment '学号,外键',
  10.        score tinyint unsigned comment '成绩',
  11.        foreign key(sid) references stuinfo(id) on delete set null on update cascade
  12. )engine=innodb;
复制代码
温馨提示:置空、级联操作中外键不能是从表的主键
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

UID
1
贡献
387
丢币
38902
主题
4607
回帖
116
注册时间
2018-9-25
最后登录
2024-4-16