SQLite - How to delete parent row while keeping the child/children rows?

南笙酒味 提交于 2019-12-24 15:45:28

问题


I understand the concepts of PRAGMA foreign_key and of ON DELETE RESTRICT/NO ACTION, but I am facing a different kind of situation.

I need to delete a parent row but keep the child row associated with it. For example:

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;

I want to achieve this while keeping the child row intact. Is this possible at all?

EDIT

The example above separates my question from this question. Example might help some people, who only understand when there is code.


回答1:


You can do this with a 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;


来源:https://stackoverflow.com/questions/29349122/sqlite-how-to-delete-parent-row-while-keeping-the-child-children-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!