gpt4 book ai didi

mysql - 如何更新 MySQL 中的级联?

转载 作者:可可西里 更新时间:2023-11-01 06:39:39 24 4
gpt4 key购买 nike

让我们看一下这个示例数据库: Example database

正如我们所见,person 取决于城市(person.city_id 是外键)。我不删除行,我只是将它们设置为非事件状态 (active=0)。设置city inactive后,如何自动设置所有依赖这个city的人都inactive?有没有比编写触发器更好的方法?

编辑:我只对将人员的行设置为非事件状态感兴趣,而不是将它们设置为事件状态。

最佳答案

这是一个使用级联外键来执行您描述的操作的解决方案:

mysql> create table city (
id int not null auto_increment,
name varchar(45),
active tinyint,
primary key (id),
unique key (id, active));

mysql> create table person (
id int not null auto_increment,
city_id int,
active tinyint,
primary key (id),
foreign key (city_id, active) references city (id, active) on update cascade);

mysql> insert into city (name, active) values ('New York', 1);

mysql> insert into person (city_id, active) values (1, 1);

mysql> select * from person;
+----+---------+--------+
| id | city_id | active |
+----+---------+--------+
| 1 | 1 | 1 |
+----+---------+--------+

mysql> update city set active = 0 where id = 1;

mysql> select * from person;
+----+---------+--------+
| id | city_id | active |
+----+---------+--------+
| 1 | 1 | 0 |
+----+---------+--------+

在 MySQL 5.5.31 上测试。

关于mysql - 如何更新 MySQL 中的级联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16779552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com