php三种外键操作

[复制链接]
查看379 | 回复0 | 2023-5-16 17:42 | 显示全部楼层 |阅读模式
php三种外键操作

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
519
贡献
14
丢币
0
主题
55
回帖
7
注册时间
2023-5-12
最后登录
2024-1-19
QQ