父表是
CREATE TABLE BHEAD (
ID INTEGER primary key asc,
DESCR TEXT,
LINECTR INT,
UNITCTR INT)
子表是
CREATE TABLE BDET (
ID INTEGER primary key asc,
BID INTEGER,
BCODE TEXT,
QTY INTEGER,
FOREIGN KEY (BID) REFERENCES BHEAD(ID) ON DELETE CASCADE
)
我也执行sql PRAGMA foreign_keys = ON;
但它不起作用;当我从BHEAD
删除一行时,其BDET
中的关联行不会消失...
为什么会这样?
答案 0 :(得分:1)
您使用的是什么版本的SQLite?
请参阅:Foreign Keys。
为了在SQLite中使用外键约束,必须在既未定义SQLITE_OMIT_FOREIGN_KEY或SQLITE_OMIT_TRIGGER的情况下编译库。
答案 1 :(得分:0)
但是,您也可以在删除级联上实施以删除所有子项 父行被删除时的行。
-- Create the test tables using ON DELETE CASCADE
DROP TABLE t3 PURGE;
--DROP TABLE t2 PURGE;
--DROP TABLE t1 PURGE;
CREATE TABLE t1 (
id NUMBER,
description VARCHAR2(50),
CONSTRAINT t1_pk PRIMARY KEY (id)
);
CREATE TABLE t2 (
id NUMBER,
t1_id NUMBER,
description VARCHAR2(50),
CONSTRAINT t2_pk PRIMARY KEY (id),
CONSTRAINT t2_t1_fk FOREIGN KEY (t1_id) REFERENCES t1 (id) ON DELETE CASCADE
);
CREATE TABLE t3 (
id NUMBER,
t2_id NUMBER,
description VARCHAR2(50),
CONSTRAINT t3_pk PRIMARY KEY (id),
CONSTRAINT t3_t2_fk FOREIGN KEY (t2_id) REFERENCES t2 (id)
);
INSERT INTO t1 VALUES (1, 't1 ONE');
INSERT INTO t2 VALUES (1, 1, 't2 ONE');
INSERT INTO t2 VALUES (2, NULL, 't2 TWO');
INSERT INTO t3 VALUES (1, 1, 't3 ONE');
INSERT INTO t3 VALUES (2, NULL, 't3 TWO');
COMMIT;
SELECT (SELECT COUNT(*) FROM t1) AS t1_count,
(SELECT COUNT(*) FROM t2) AS t2_count,
(SELECT COUNT(*) FROM t3) AS t3_count
FROM dual;
DELETE FROM t3;
rollback;
truncate table t1 ;
rollback;
truncate table t1 CASCADE;