SQLite - 如何在保留子/子行的同时删除父行?

时间:2015-03-30 14:38:59

标签: sqlite foreign-keys

我理解PRAGMA foreign_keyON DELETE RESTRICT/NO ACTION的概念,但我面临着另一种情况。

我需要删除父行,但保持子行与之关联。例如:

CREATE TABLE A(id, name);
INSERT INTO A(id, name) VALUES (1, "Loreum");

CREATE TABLE B(id, id_A, name) FOREIGN KEY(id_A) REFERENCES A(id);
INSERT INTO B(id, id_A, name) VALUES (1, 1, "Opium");
DELETE FROM A WHERE id = 1;

我希望在保持子行完整的同时实现此。这有可能吗?

修改

上面的示例将我的问题与this question分开。示例可能会帮助一些只知道何时有代码的人。

1 个答案:

答案 0 :(得分:1)

您可以使用deferred foreign key constraint

执行此操作
PRAGMA foreign_keys = on;
CREATE TABLE A(id PRIMARY KEY, name);
INSERT INTO A(id, name) VALUES (1, "Loreum");
CREATE TABLE B(id, id_A, name, FOREIGN KEY(id_A) REFERENCES A(id) DEFERRABLE INITIALLY DEFERRED);
INSERT INTO B(id, id_A, name) VALUES (1, 1, "Opium");

BEGIN;
DELETE FROM A WHERE id = 1;
INSERT INTO A(id, name) VALUES (1, "another Loreum");
COMMIT;