Delete recursive children

徘徊边缘 提交于 2019-12-10 20:10:42

问题


I have the following sql that gets me all the children and grandchildren of a root 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

Thing is I want the records selected to be deleted. Something like delete from forumposts fp where fp.id=(last select from the code above) but that doesn't work(I get syntax error at or near "DELETE"). This is my first time ever using recursive and I must be missing something. Any help is appreciated.


回答1:


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


来源:https://stackoverflow.com/questions/10381243/delete-recursive-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!