我们来看看这个示例数据库:

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

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

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

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,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上测试过.

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。