我有两个表p,u如下所示:(PostgreSQL 9.3)
p
u
CREATE TABLE p ( pid integer NOT NULL, uid integer, CONSTRAINT p_fkey FOREIGN KEY (uid) REFERENCES u (uid) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE RESTRICT ); CREATE TABLE u ( uid integer NOT NULL, pid integer, CONSTRAINT u_fkey FOREIGN KEY (pid) REFERENCES p (pid) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE RESTRICT );
在p我有:
pid uid 161556 176266
在u我有
uid pid 176266 161556
我想要做:
DELETE FROM u WHERE uid=176266; DELETE FROM p WHERE pid=113116;
但是我不能。
错误:对表“ u”的更新或删除违反了表“ p”上的外键约束“ p_fkey”。详细信息:仍从表“ p”中引用键(uid)=(176266)。
我了解错误,但不知道该怎么做才能删除。
有什么建议吗?
您可以在一条语句中删除两行:
WITH x AS ( DELETE FROM u WHERE uid = 176266 ) DELETE FROM p WHERE pid = 113116;
之所以有效,IMMEDIATE是因为在语句的末尾检查了约束。该语句将删除两行,并在该语句的末尾满足所有完整性约束。
IMMEDIATE