3

我有以下 sql,它可以让我获得根论坛帖子的所有子孙。

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

事情是我希望删除选择的记录。类似于从论坛帖子 fp 中删除的内容,其中 fp.id=(最后从上面的代码中选择),但这不起作用(我在“删除”处或附近出现语法错误)。这是我第一次使用递归,我一定遗漏了一些东西。任何帮助表示赞赏。

4

1 回答 1

6

You can simply use the DELETE statement instead of SELECT to do your job:

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

Other combinations possible, like deleting from master table based on the deleted rows in the child one, check out the documentation.

EDIT: For PostgresSQL versions prior to 9.1, you can use your initial query like this:

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
);
于 2012-04-30T09:32:37.207 回答