我在 mysql 数据库上工作,我想引用复合键的一部分(其中有 2 个字段)并避免 mysql 在删除引用条目时删除引用条目,如果有高跷 a引用表中复合键的一部分。
问题来了:
两个表:
- T1(Some_PK, #Pointer_To_PKA, some_field)
- T2(PKA, PKB, Some_field)
T2 有一个复合 key ,由两个字段PKA 和PKB
- 在 T1 中有一个外键约束引用了 T2 的字段 PKA 而不是 PKB(仅引用了一半的组合键)。
问题是,当我在 T2 中删除一行时,'ON CASCADE DELETE' 约束删除了 T1 中的行,该行引用了在 T2 中删除的行,但该行(来自 T1)在删除之前还引用了 T2 中的其他字段:
============= T2 =============
[PKA] | [PKB] | Some_field
------------------------------
1 | 1 | Some content
1 | 2 | abcdefgh
2 | 3 | zefhds
______________________________
==================== T1 ========================
[Some_PK] | #Pointer_To_PKA | Some_field
------------------------------------------------
A | 1 | Lorem ipsum
B | 2 | other content
C | 1 | dhtshfgnfn
________________________________________________
使用上面的示例,当我从 T2 中删除第一行时(1、1、'Some content'),第一行和T1 的第三行保留下来,因为 T2(第二行)中仍有一个条目包含 T1 引用的复合键的一半。
有人知道如何处理吗?
最佳答案
我几乎从不说“不要那样做”。
但是don't do that .
. . . the system does not enforce a requirement that the referenced columns be UNIQUE or be declared NOT NULL. The handling of foreign key references to nonunique keys or keys that contain NULL values is not well defined for operations such as UPDATE or DELETE CASCADE. You are advised to use foreign keys that reference only UNIQUE (including PRIMARY) and NOT NULL keys.
您对 PKA 没有唯一约束。因此,请遵循文档中的建议。重新设计您的表格。
关于php - 仅在没有引用时引用复合键的一个字段和 'ON DELETE CASCADE',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18098706/