How to do a cascading update?

前端 未结 1 875
时光说笑
时光说笑 2021-02-07 13:54

I have a group of tables with columns that have foreign key constraints on a user name column in another table. I\'ve been instructed not to add ON UPDATE CASCADE t

相关标签:
1条回答
  • 2021-02-07 14:35

    In Postgres (and other RDBMs) cascading updates apply exclusively to foreign keys. Example:

    create table groups (
        group_id int primary key
    );
    
    create table users (
        user_id int primary key, 
        group_id int references groups on update cascade
    );
    
    insert into groups values (1);
    insert into users values (1, 1);
    update groups set group_id = 10 where group_id = 1;
    
    select * from users;
    
     user_id | group_id 
    ---------+----------
           1 |       10
    (1 row) 
    

    In fact, other options are not needed. If you feel the need to do this for a column which is not a foreign key, it means that the model is poorly designed (it is not normalized). On the other hand, the possibility of selective cascaded update of foreign keys does not solve any practical problem but rather brakes the general rules.

    0 讨论(0)
提交回复
热议问题