简体   繁体   English

MySQL - ON更新CASCADE + foreign_key_checks = 0

[英]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. 部分原因是将所有外键更改为ON UPDATE CASCADE ,然后递增所有主键以避免冲突并保持外键指针正常工作。

My problem is that sometimes there are some orphaned rows with broken FK, so following query: 我的问题是,有时候有一些孤立的行有破坏的FK,所以跟着查询:

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!) 失败如下: ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ...(尽管我甚至没有考虑触摸外键列!)

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. 设置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 ? 有没有办法触发级联,或者在没有设置foreign_key_checks=0情况下执行FK损坏的行的更新? UPDATE IGNORE doesn't solve this problem :( UPDATE IGNORE没有解决这个问题:(

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 否则将fk字段更新为null

After that your operations will work just fine. 之后,您的操作将正常运行。

Additional information: 附加信息:

If the column is NOT NULL , it means this the relation is a 1*. 如果NOT NULL ,则表示关系为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. 在这种情况下,您必须在父表中添加一个虚拟行(例如,“VIRTUAL PARENT”行),并将指向未显存父项的所有fks更新到此表。 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. 如果您认为1 *不是必需的(0 *对于您的技术/应用层来说已足够),那么只需将列设置为可为空即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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