9

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

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

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

4

2 回答 2

18

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

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

于 2013-05-27T20:01:37.647 回答
3

也许您应该重新考虑如何将一个人定义为活跃的。。与其将活跃定义两次,不如将其保留在城市表中,并让您的 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
于 2013-05-27T19:45:37.003 回答