在Postgres中使用自引用外键删除

时间:2018-05-30 12:35:18

标签: sql postgresql common-table-expression recursive-query

使用带有自引用外键的表:

CREATE TABLE tree (  
    id INTEGER,
    parent_id INTEGER,
    PRIMARY KEY (id)  
);

ALTER TABLE tree 
   ADD CONSTRAINT fk_tree
   FOREIGN KEY (parent_id) 
   REFERENCES tree(id);

INSERT INTO tree (id, parent_id)
VALUES (1, null),
       (2, 1),
       (3, 1),
       (4, 2),
       (5, null),
       (6, 5);

我希望通过递归遍历树来删除分支,因为我可能不会使用ON DELETE CASCADE

WITH RECURSIVE branch (id, parent_id) AS (
      SELECT id, parent_id
      FROM tree
      WHERE id = 1 -- Delete branch with root id = 1

      UNION ALL SELECT c.id, c.parent_id
      FROM tree c -- child
      JOIN branch p -- parent
            ON c.parent_id = p.id
)
DELETE FROM tree t
USING branch b
WHERE t.id = b.id;

使用Postgres中的公用表表达式是否安全,或者我是否必须担心删除记录的顺序? Postgres会将所有行删除为单个集合,还是逐个删除?

如果答案取决于版本,哪个版本的删除安全?

1 个答案:

答案 0 :(得分:1)

不,您不必担心选择中的订单。

外键(与唯一约束不同)是每个语句,而不是每行。并且公共表表达式仍然是单个语句,即使您有多个SELECT和DELETE也是如此。

因此,如果语句结束时所有约束仍然有效,则一切正常。

您可以通过以下简单测试轻松看到这一点:

CREATE TABLE fk_test
(
  id          integer PRIMARY KEY,
  parent_id   integer,
  FOREIGN KEY (parent_id) REFERENCES fk_test (id)
);

INSERT INTO fk_test (id, parent_id) 
VALUES 
  (1, null),
  (2, 1),
  (3, 2),
  (4, 1);

因此,即使在"错误的"中指定了ID,以下显然仍然有效。顺序:

DELETE FROM fk_test
WHERE id IN (1,2,3,4);

以下有效 - 显示CTE仍然是单一陈述:

with c1 as (
  delete from fk_test where id = 1
), c2 as (
  delete from fk_test where id = 2
), c3 as (
  delete from fk_test where id = 3
)
delete from fk_test where id = 4;