Generate SQL to update primary key

后端 未结 4 1480
滥情空心
滥情空心 2020-12-15 06:56

I want to change a primary key and all table rows which reference to this value.

# table master
master_id|name
===============
foo|bar

# table detail
detail         


        
4条回答
  •  时光取名叫无心
    2020-12-15 07:14

    The easiest way to deal with primary key changes - by far - is to ALTER your referring foreign key constraints to be ON UPDATE CASCADE.

    You are then free to update the primary key values, and the changes will cascade to child tables. It can be a very slow process due to all the random I/O, but it will work.

    You do need to watch out not to violate uniqueness constraints on the primary key column during the process.

    A fiddlier but faster way is to add a new UNIQUE column for the new PK, populate it, add new columns to all the referring tables that point to the new PK, drop the old FK constraints and columns, then finally drop the old PK.

提交回复
热议问题