How to update on cascade in MySQL?

后端 未结 2 1331
臣服心动
臣服心动 2020-12-31 15:29

Let\'s look at this example database: \"Example

As we can see, person depends on the city (person.ci

2条回答
  •  醉话见心
    2020-12-31 15:52

    Here's a solution that uses cascading foreign keys to do what you describe:

    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 |
    +----+---------+--------+
    

    Tested on MySQL 5.5.31.

提交回复
热议问题