如何在MySQL中级联更新?

时间:2013-05-27 19:40:20

标签: mysql sql database

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

正如我们所看到的,人依赖于城市(person.city_id是外键)。我不删除行,我只是将它们设置为非活动状态(active = 0)。设置城市无效后,如何自动设置所有依赖此城市的人员?有没有比编写触发器更好的方法?

编辑:我只对将人的行设置为非活动而不是将其设置为活动感兴趣。

2 个答案:

答案 0 :(得分:13)

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

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上测试。

答案 1 :(得分:2)

也许你应该重新考虑如何定义一个人是活跃的..你应该将它保留在city表中并让你的SELECT语句返回Person WHERE city.active = 1 ..

但如果你必须......你可以这样做:

UPDATE city C
LEFT JOIN person P ON C.id = P.city
SET C.active = 0 AND P.active = 0
WHERE C.id = @id