简体   繁体   中英

SQLite on delete cascade with two foreign keys

If I have two tables and a third table that is the foreign key to the first and second table as follows:

CREATE TABLE A
(
    name    VARCHAR(255),
    PRIMARY KEY(name)
);

CREATE TABLE B
(
    number  INT,
    PRIMARY KEY(number)
);

CREATE TABLE C
(
    cname   VARCHAR(255),
    cnumber INT,
    PRIMARY KEY(cname, cnumber),
    FOREIGN KEY(cname) REFERENCES A(name) ON DELETE CASCADE,
    FOREIGN KEY(cnumber) REFERENCES B(number) ON DELETE CASCADE
);

INSERT INTO A values("John");
INSERT INTO A values("Sam");
INSERT INTO B values(1);
INSERT INTO B values(2);
INSERT INTO C values("John", 1);
INSERT INTO C values("John", 2);
INSERT INTO C values("Sam", 2);

I want to delete 1 such that (1) is deleted from B and the entry (John,1) is also deleted from C and (John) in A is also deleted.

Because there is DELETE CASCADE I should be able to do it but:

DELETE FROM B WHERE number = 1;

only removes 1 from B and (John,1) from C but (John) in A is not deleted.

So far I was only able to delete an entry from 1 table and have the other table with the foreign key to delete its entry, but I'm not sure how to delete another table that also references this table with the foreign key with JUST 1 query.

What you want to achieve is not possible using foreign keys, at least not the way you have set it up.

Table C has a foreign-key on A , so entries from C will be removed if the corresponding key in A is removed, not the other way around. If you want to delete from A when entries in C are deleted, A would need to have a foreign key on C .

BUT this requires, that cname would be a unique key in C . Sqlite will allow you to set up and insert data, but it won't allow you to delete if there are multiple entries for something that is referenced as foreign-key.

PRAGMA foreign_key = true;
CREATE TABLE B
(
    number  INT,
    PRIMARY KEY(number)
);

CREATE TABLE C
(
    cname   VARCHAR(255),
    cnumber INT,
    PRIMARY KEY(cname, cnumber),
    FOREIGN KEY(cnumber) REFERENCES B(number) ON DELETE CASCADE
);

CREATE TABLE A
(
    name    VARCHAR(255),
    PRIMARY KEY(name)
    FOREIGN KEY(name) REFERENCES C(came) ON DELETE CASCADE
);

INSERT INTO B values(1);
INSERT INTO B values(2);
INSERT INTO C values("John", 1);
INSERT INTO C values("John", 2);
INSERT INTO C values("Sam", 2);
INSERT INTO A values("John");
INSERT INTO A values("Sam");

INSERT INTO C values("John", 1);
INSERT INTO C values("John", 2);
INSERT INTO C values("Sam", 2);

DELETE FROM B where number = 1;
Error: foreign key mismatch - "A" referencing "C"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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