删除/选择postgresql中的层次结构数据

时间:2016-05-16 02:08:58

标签: sql postgresql recursion hierarchy postgresql-9.4

我有表comment,我想通过输入id删除并删除所有子项,

以下两个查询都不删除所有层次结构数据,只删除self和一个子行......

with闭包中选择递归时有什么问题吗?

评论

id | parent_comment_id
1  | 
2  | 1
3  | 2
4  |

查询1

WITH RECURSIVE coH AS (
  SELECT co.id,
    co.id AS rootId
    FROM comment co

  UNION ALL

  SELECT coChild.id,
    coChild.parent_comment_id as parentCommentId
    FROM comment coChild
    JOIN coH coP ON coP.id = coChild.parent_comment_id
)
DELETE FROM comment WHERE id IN (
  SELECT id FROM coH WHERE rootId = $1
)

查询2

DELETE FROM comment WHERE id IN (
  WITH RECURSIVE coH AS (
    SELECT co.id,
      co.id AS rootId
      FROM comment co

    UNION ALL

    SELECT coChild.id,
      coChild.parent_comment_id as parentCommentId
      FROM comment coChild
      JOIN coH coP ON coP.id = coChild.parent_comment_id
  )

  SELECT id FROM coH WHERE rootId = $1
)

更新

var dbQuery = `DELETE FROM comment WHERE id IN (
  WITH RECURSIVE coH (id, parentCommentId, rootId) AS (
    SELECT co.id,
      co.parent_comment_id as parentCommentId,
      co.id AS rootId
      FROM comment co

    UNION ALL

    SELECT coChild.id,
      coChild.parent_comment_id as parentCommentId,
      coP.rootId
      FROM comment coChild
      JOIN coH coP ON coP.id = coChild.parent_comment_id
  )

  SELECT id FROM coH WHERE rootId = $1
)`;

1 个答案:

答案 0 :(得分:1)

保持简单,将参数放在递归的初始查询中:

with recursive cbase as (
    select 1 as id -- select $1 as id

    union all

    select child.id
    from comment as child
    join cbase on cbase.id = child.parent_comment_id
)
delete from comment 
where id in (select * from cbase)
returning id;

 id 
----
  1
  2
  3
(3 rows)

DELETE 3