2012-04-30 149 views
3

我有以下的SQL,让我所有的根forumpost的子孙。删除递归子

with recursive all_posts (id, parentid, root_id) as 
       (
       select t1.id, 
       t1.parent_forum_post_id as parentid, 
       t1.id as root_id 
       from forumposts t1 

       union all 

       select c1.id, 
       c1.parent_forum_post_id as parentid, 
       p.root_id 
       from forumposts 
       c1 
       join all_posts p on p.id = c1.parent_forum_post_id 
       ) 

       select fp.id 
       from forumposts fp inner join all_posts ap 
       on fp.id=ap.id 
       where 
       root_id=1349 
       group by fp.id 

事情是我想选择的记录被删除。类似于从forumposts fp删除其中fp.id =(上次从以上的代码中选择),但不起作用(我在DELETE处或附近获得语法错误)。这是我第一次使用递归,我必须失去一些东西。任何帮助表示赞赏。

回答

6

您可以简单地使用DELETE语句而不是SELECT做你的工作:

with recursive all_posts (id, parentid, root_id) as (
    select t1.id, 
    t1.parent_forum_post_id as parentid, 
    t1.id as root_id 
    from forumposts t1 

    union all 

    select c1.id, 
    c1.parent_forum_post_id as parentid, 
    p.root_id 
    from forumposts 
    c1 
    join all_posts p on p.id = c1.parent_forum_post_id 
) 
DELETE FROM forumposts 
WHERE id IN (SELECT id FROM all_posts WHERE root_id=1349); 

其他可能的组合,就像从主表中删除基于孩子一个,check out the documentation被删除的行。

编辑:对于PostgreSQL的以前的版本9.1,你可以用你的初始查询是这样的:

DELETE FROM forumposts WHERE id IN (
    with recursive all_posts (id, parentid, root_id) as (
     select t1.id, 
     t1.parent_forum_post_id as parentid, 
     t1.id as root_id 
     from forumposts t1 

     union all 

     select c1.id, 
     c1.parent_forum_post_id as parentid, 
     p.root_id 
     from forumposts c1 
     join all_posts p on p.id = c1.parent_forum_post_id 
    ) 
    select id from all_posts ap where root_id=1349 
); 
+0

感谢您的答复。这是我已经尝试过的,并且在“DELETE”处或附近出现语法错误。这就是让我发布这个问题的原因。对此有何想法?谢谢。 – Fofole

+0

你正在使用哪个版本的PostgreSQL?看起来你在9.1版之前,对吧? – vyegorov

+0

我使用1.14.2,我试过了 - >关于 – Fofole