Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete recursive children

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.

like image 231
Fofole Avatar asked Jun 23 '26 08:06

Fofole


1 Answers

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
);
like image 170
vyegorov Avatar answered Jun 27 '26 23:06

vyegorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!