如果从父表中删除行,如何从子表中删除该行?

时间:2013-07-25 12:31:26

标签: sqlite

这是一个简单的shema:

sqlite> .schema recordtypes
CREATE TABLE recordtypes (record_id text primary key);
sqlite> .schema headers
CREATE TABLE headers (header_id text primary key);
sqlite> .schema record_to_headers
CREATE TABLE record_to_headers (id INTEGER, recordid TEXT, headerid TEXT, FOREIGN KEY(recordid) REFERENCES recordtypes(record_id), FOREIGN KEY(headerid) REFERENCES headers(header_id));

然后我将值插入recordtypes,然后插入record_to_headers

sqlite> insert into recordtypes values("test");
sqlite> insert into record_to_headers values (1, "test", "yeah");

然后我从recordtypes表中删除“test”,期望它也从record_to_headers表中删除,但这种情况从未发生过:

sqlite> delete from recordtypes where record_id = "test";
sqlite> select * from recordtypes;
sqlite> select * from record_to_headers;
1|test|yeah

如果我从recordtypes表中删除它,我也需要行为,它也会从record_to_header表中删除。请告知如何操作。非常感谢。

1 个答案:

答案 0 :(得分:2)

使用SQLLite并没有太多经验,但从documentation我可以看到,SQLLite支持外键级联。这将在删除父行时删除子行:

FOREIGN KEY(headerid) REFERENCES headers(header_id) ON DELETE CASCADE

您应该查阅文档以了解是否需要事先在SQLLite中配置。