代码之家  ›  专栏  ›  技术社区  ›  user1575921

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

  •  2
  • user1575921  · 技术社区  · 8 年前

    我有桌子 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
    )`;
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   klin    8 年前

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

    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