[英]i used the program SQL Fiddle and it keeps telling me that the table doesn't exist,what can i do to fix the two tables referencing each other?
[英]SQL - How do I delete two entities referencing each other
所以我有两个实体相互引用, parent
, child
。
如果parent
被删除,则必须删除child
,但在parent
仍然引用parent
时,不能删除parent
。
这是我给出的两个限制:
ALTER TABLE public.parent
ADD CONSTRAINT parent__child_id__fk
FOREIGN KEY (child_id) REFERENCES child(id)
ON DELETE CASCADE
;
ALTER TABLE public.child
ADD CONSTRAINT child__parent_code__id__fk
FOREIGN KEY (parent_code, id) REFERENCES parent(code, child_id)
ON UPDATE CASCADE
ON DELETE RESTRICT
DEFERRABLE INITIALLY DEFERRED
;
我现在要删除parent
(以及相应的child
)...
SQL Error [23503]:
ERROR: update or delete on table "parent" violates foreign key constraint
"child__parent_code__id__fk" on table "child"
Detail: Key (code, child_id)=(A0B7EBF6-3_DELETE_ME, 10)
is still referenced from table "child".
Whoop-dee-doo ......
是的,我试图删除的血腥条目引用它...
(我知道因为parent.code
有一个独特的约束)
看起来我可以删除条目,如果我将child
的fk设置为ON DELETE CASCADE
,但这似乎不是我的脖子上想要的人,这是“如果你删除parent
删除它的child
, ,如果你删除了一个有parent
的child
,请不要“。
我该如何实现这一目标?
使用CTE从一个语句中删除两个表:
WITH x AS (
DELETE FROM parent
WHERE ...
RETURNING id
)
DELETE FROM child
WHERE ...;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.