我理解PRAGMA foreign_key
和ON 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分开。示例可能会帮助一些只知道何时有代码的人。
答案 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;