在 SQLite 中删除多个父键和外键的行

Delete rows of multiple parent and foreign keys in SQLite

我是 SQLite 的初学者。我试图从 TableA 中删除该行,它也应该删除相关的连接 table 行。

TableA
id
name

TableB
id
tbidA ref key TableA(id)
name
tbidC ref key TableC(id)
tbidD ref key TableD(id)
tbidE ref key TableE(id)

TableD
id
name

TableE
id
name

TableF
id
name

TableG
id
tbidE ref key TableE(id)
name

我试过 JOINS 但它抛出语法错误。然后我发现SQLite不支持DELETE JOINS。上面的table结构如何使用ON DELETE CASCADE

我相信下面的代码会像您want/have描述的那样:-

DROP TABLE tableg;
DROP TABLE tableb;
DROP TABLE tablea;
DROP TABLE tablec;
DROP TABLE tabled;
DROP TABLE tablee;
CREATE TABLE IF NOT EXISTS tablea (id INTEGER PRIMARY KEY, name TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS tablec (id INTEGER PRIMARY KEY, name TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS tabled (id INTEGER PRIMARY KEY, name TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS tablee (id INTEGER PRIMARY KEY, name TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS tablef (id INTEGER PRIMARY KEY, name TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS tableb (id INTEGER PRIMARY KEY, 
    tbida REFERENCES tablea(id) ON DELETE CASCADE, 
    name,
    tbidc REFERENCES tablec(id) ON DELETE CASCADE,
    tbidd REFERENCES tabled(id) ON DELETE CASCADE,
    tbide REFERENCES tablee(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS tableg (id INTEGER PRIMARY KEY, 
    name TEXT,
    tbide REFERENCES tablee(id) ON DELETE CASCADE
);
INSERT OR IGNORE INTO tablea (name) VALUES('A-Fred'),('A-Bert'),('A-Mary'),('A-Sue'),('A-Ann'),('A-Jane'),('A-Tom');
INSERT OR IGNORE INTO tablec (name)  VALUES('C-Fred'),('C-Bert'),('C-Mary'),('C-Sue'),('C-Ann'),('C-Jane'),('C-Tom');
INSERT OR IGNORE INTO tabled (name)  VALUES('D-Fred'),('D-Bert'),('D-Mary'),('D-Sue'),('D-Ann'),('D-Jane'),('D-Tom');
INSERT OR IGNORE INTO tablee (name)  VALUES('E-Fred'),('E-Bert'),('E-Mary'),('E-Sue'),('E-Ann'),('E-Jane'),('E-Tom');

INSERT OR IGNORE INTO tableb (name, tbida, tbidc, tbidd, tbide) VALUES
    ('B-X1',1,1,1,1),
    ('B-Y1',1,3,4,5),
    ('B-Z1',6,2,2,2)
;
INSERT OR IGNORE INTO tableg (name, tbide) VALUES('G-X1',5),('G-Y1',3),('G-Z1',4);

SELECT * FROM tablea 
    JOIN tableb ON tablea.id = tbida
    JOIN tablec ON tablec.id = tbidc
    JOIN tabled ON tabled.id - tbidd
    JOIN tablee ON tablee.id = tableb.tbide
    JOIN tableg ON tableg.id = tablee.id
;

DELETE FROM tablea WHERE id = 1; -- <<<<<<<<<<

SELECT * FROM tablea 
    JOIN tableb ON tablea.id = tbida
    JOIN tablec ON tablec.id = tbidc
    JOIN tabled ON tabled.id - tbidd
    JOIN tablee ON tablee.id = tableb.tbide
    JOIN tableg ON tableg.id = tablee.id
;

第一个结果是(即加载相关数据(按照完全加入tables)):-

从 tableA 中删除第一行后的第二个结果(即 A-Fred):-

即ON DELETE CASCADE在DELETE FROM tablea WHERE id = 1;被操作时执行分层删除