为什么ON DELETE CASCADE不删除引用的记录?

时间:2016-08-02 15:27:53

标签: mysql

我使用下面显示的代码创建了SQLFiddle。问题是在DELETE语句之后,相关的credit_card记录也应该被删除。

CREATE TABLE person (
  id BIGINT AUTO_INCREMENT PRIMARY KEY
);

CREATE TABLE credit_card (
  id BIGINT AUTO_INCREMENT PRIMARY KEY
);

CREATE TABLE person_credit_card (
  person_id BIGINT NOT NULL,
  credit_card_id BIGINT NOT NULL UNIQUE, -- Please note that this is UNIQUE
  PRIMARY KEY(person_id, credit_card_id),

  CONSTRAINT fk__person_credit_card__person
    FOREIGN KEY (person_id)
    REFERENCES person(id), 

  KEY pkey (credit_card_id),
  CONSTRAINT fk__person_credit_card__credit_card
    FOREIGN KEY (credit_card_id)
    REFERENCES credit_card(id) 
      ON DELETE CASCADE 
      ON UPDATE CASCADE
);

INSERT INTO person (id) VALUES (1);
INSERT INTO credit_card (id) VALUES (1);
INSERT INTO person_credit_card (person_id, credit_card_id) VALUES (1, 1);

DELETE FROM person_credit_card WHERE credit_card_id = 1;

我不确定为什么这不起作用。 UNIQUE上的credit_card_id约束可能

+--------------------------------------+
| person_credit_card                   |
+--------------------------------------+
| person_id | credit_card_id           |
+--------------------------------------+
| 1         | 1                        |
+--------------------------------------+
| 2         | 1                        |
+--------------------------------------+

那么我在这里做错了什么以及如何让它发挥作用?

我也尝试过例如删除person并删除所有credit_card条记录(请参阅此另一个SQLFiddle):

CREATE TABLE person (
  id BIGINT AUTO_INCREMENT PRIMARY KEY
);

CREATE TABLE credit_card (
  id BIGINT AUTO_INCREMENT PRIMARY KEY
);

CREATE TABLE person_credit_card (
  person_id BIGINT NOT NULL,
  credit_card_id BIGINT NOT NULL UNIQUE,
  PRIMARY KEY(person_id, credit_card_id),

  CONSTRAINT fk__person_credit_card__person
    FOREIGN KEY (person_id)
    REFERENCES person(id)
      ON DELETE CASCADE 
      ON UPDATE CASCADE, 

  CONSTRAINT fk__person_credit_card__credit_card
    FOREIGN KEY (credit_card_id)
    REFERENCES credit_card(id) 
      ON DELETE CASCADE 
      ON UPDATE CASCADE
);

INSERT INTO person (id) VALUES (1);
INSERT INTO person (id) VALUES (2);
INSERT INTO credit_card (id) VALUES (1);
INSERT INTO credit_card (id) VALUES (2);
INSERT INTO credit_card (id) VALUES (3);

INSERT INTO person_credit_card (person_id, credit_card_id) VALUES (1, 1);
INSERT INTO person_credit_card (person_id, credit_card_id) VALUES (1, 2);
INSERT INTO person_credit_card (person_id, credit_card_id) VALUES (2, 3);

DELETE FROM person WHERE id = 1;

但结果是只有分辨率表丢失了条目,但credit_card记录仍在那里。

2 个答案:

答案 0 :(得分:1)

来自documentation

  

CASCADE:删除或更新父表中的行,然后   自动删除或更新子表中的匹配行。   支持ON DELETE CASCADE和ON UPDATE CASCADE。

答案 1 :(得分:1)

从person_credit_card删除不会级联人员或credit_card。 Cascade通过删除/更新引用要删除的记录的表中的记录来工作。 换句话说,由于人没有参考person_credit_card的列,因此不会删除它。