2012-04-30 183 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