sql - 在 postgresql 中删除/选择层次结构数据

标签 sql postgresql recursion hierarchy postgresql-9.4

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

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

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
)`;

最佳答案

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

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    

关于sql - 在 postgresql 中删除/选择层次结构数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37245734/

相关文章:

postgresql - 如何将oracle数据迁移到postgres?

database - DBUnit 坚持为未指定的值插入 null,但我希望使用 DB 默认值

postgresql - 如何让 PostgreSQL 恢复以接受数据中的 ";"和 "\N"作为字符串的一部分?

c++ - 我想通过使用模板元编程从变量 args 中剥离参数

sql - 在 SQL 中排列值

sql - ** 在 SQL Server Management Studio 中查看执行计划时的受限文本 **

c# - 如何避免在 WPF 中递归触发事件?

xml - 如何使用 XSLT 递归删除一些 xml 元素

sql - 用 INT IDENTITY PK 替换 GUID PK

sql - 使用合并的逗号分隔列表