php - 仅在没有引用时引用复合键的一个字段和 'ON DELETE CASCADE'

标签 php mysql foreign-keys composite-primary-key cascading-deletes

我在 mysql 数据库上工作,我想引用复合键的一部分(其中有 2 个字段)并避免 mysql 在删除引用条目时删除引用条目,如果有高跷 a引用表中复合键的一部分。

问题来了:

  • 两个表:

    • T1(Some_PK, #Pointer_To_PKA, some_field)
    • T2(PKA, PKB, Some_field)
  • T2 有一个复合 key ,由两个字段PKAPKB

  • 在 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 中删除第一行时(11、'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/

相关文章:

javascript - php echo后显示黑屏

php - 数据库查询返回: Check if a parameter is an array or an object

javascript - 如何根据 MySQL 数据库中存储的坐标显示动画多个标记

sql - 使用复杂的 WHERE 语句更新 Liquibase 中的行

django - 在 Django Rest Framework 中,如何限制序列化的外键对象数量

javascript - Laravel 500 错误,Base64 图像,Ajax 和数组的

php - 多个sql查询的单个查询

mysql - 返回表中未使用的所有日期的 SQL 查询

mysql - Drupal 7 - EntityFieldQuery - 与 mysql FIELD(...) 一起使用进行自定义订单

sql - PostgreSQL 外键约束违反继承