简体   繁体   中英

MySQL - ON update CASCADE + foreign_key_checks = 0

I am developing a tool to merge two databases with the same schema but different data.

Part of it is changing all foreign keys to ON UPDATE CASCADE , then incrementing all the Primary Keys to avoid conflicts and keep foreign keys pointers working.

My problem is that sometimes there are some orphaned rows with broken FK, so following query:

UPDATE table set pk = pk + 1000000

fails like this: ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ... (despite I'm not even thinking about touching foreign key column!)

I wanted to turn that off by:

Set foreign_key_checks=0

but then related foreign keys are not updated. I've made a quick test and cascades are not working after setting foreign_key_checks=0.

Is there any way to trigger cascades, or perform an update of a row with broken FK without setting foreign_key_checks=0 ? UPDATE IGNORE doesn't solve this problem :(

You should first fix referential integrity.

  1. Delete orphan rows if the relation is a composition type
  2. update the fk field to null otherwise

After that your operations will work just fine.

Additional information:

If the column is NOT NULL , it means this the relation is a 1*. In this case, you have to add a virtual row in the parent table (say, "VIRTUAL PARENT" row) and update all fks pointing to an unexisting parent to this one. This will allow you later to proceed the datas and moreover to retrieve them easily.

If you think the 1* is not necessary (0* would be enough for your technical / applicative layer) then just set the column as nullable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM