I've created a SQLFiddle with the code shown below. The problem is that after the DELETE
statement the associated credit_card
record is supposed to be deleted as well.
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;
I'm not sure why this is not working. With the UNIQUE
constraint on the credit_card_id
this is not possible:
+--------------------------------------+
| person_credit_card |
+--------------------------------------+
| person_id | credit_card_id |
+--------------------------------------+
| 1 | 1 |
+--------------------------------------+
| 2 | 1 |
+--------------------------------------+
So what am I doing wrong here and how can I make it work?
I also tried to e.g. delete a person
and remove all his credit_card
records (see this other 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;
but the outcome is that only the resolution table is losing its entries but the credit_card
records are still there.