外键的置空、级联操作
# 外键如何设定置空
和级联
操作?
置空和级联一般在创建表时进行设置。
# 关键字
在删除的时候:on delete
在更新的时候:on update
置空:set null
级联:cascade
# 创建主表
create table if not exists student(
stu_id int primary key auto_increment comment 'student表主键stu_id',
name varchar(30) comment '学生姓名name'
);
1
2
3
4
2
3
4
插入数据到
student
表insert into student values (null, 'Jim'), (null, 'Tom'), (null, 'Anna'), (null, 'Emma');
1
2
3
4
5查询
student
表+--------+------+ | stu_id | name | +--------+------+ | 1 | Jim | | 2 | Tom | | 3 | Anna | | 4 | Emma | +--------+------+
1
2
3
4
5
6
7
8
# 创建子表
create table if not exists eatery_order(
id int primary key auto_increment comment 'eatery_order主键',
money decimal(10,4) default '0.0' comment '消费金额',
stu_id int comment 'eatery_order表外键',
foreign key (stu_id) references student(stu_id) on delete set null on update cascade
);
1
2
3
4
5
6
2
3
4
5
6
# 关键语句
foreign key (stu_id) references student(stu_id) on delete set null on update cascade
1
解释:
on delete set null
:在主表删除记录时,本表外键值置空null
on update cascade
:在主表更新记录时,本表外键值同步更新
插入数据到
eatery_order
表insert into eatery_order values (null, 7, 1), (null, 11, 3), (null, 11, 3), (null, 20, 4), (null, 7, 2), (null, 7, 4);
1
2
3
4
5
6
7查询
eatery_order
表+----+---------+--------+ | id | money | stu_id | +----+---------+--------+ | 1 | 7.0000 | 1 | | 2 | 11.0000 | 3 | | 3 | 11.0000 | 3 | | 4 | 20.0000 | 4 | | 5 | 7.0000 | 2 | | 6 | 7.0000 | 4 | +----+---------+--------+
1
2
3
4
5
6
7
8
9
10
# 来感受置空
和级联
操作的魅力吧
# 置空
删除
student
表中的一些记录:delete from student where name='Emma';
1查询
eatery_order
表+----+---------+--------+ | id | money | stu_id | +----+---------+--------+ | 1 | 7.0000 | 1 | | 2 | 11.0000 | 3 | | 3 | 11.0000 | 3 | | 4 | 20.0000 | NULL | | 5 | 7.0000 | 2 | | 6 | 7.0000 | NULL | +----+---------+--------+
1
2
3
4
5
6
7
8
9
10可以看到在
eatery_order
表中,原本为4
的stu_id
,现在都变成了null
。
# 级联
更新
student
表中的一些记录:update student set stu_id=456 where stu_id=3;
1查询
eatery_order
表+----+---------+--------+ | id | money | stu_id | +----+---------+--------+ | 1 | 7.0000 | 1 | | 2 | 11.0000 | 456 | | 3 | 11.0000 | 456 | | 4 | 20.0000 | NULL | | 5 | 7.0000 | 2 | | 6 | 7.0000 | NULL | +----+---------+--------+
1
2
3
4
5
6
7
8
9
10可以看到在
eatery_order
表中,原本为3
的stu_id
,现在都变成了456
。
编辑 (opens new window)
上次更新: 2022/09/26, 16:55:15