我有以下sql,它让我所有的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
我希望删除所选的记录。像从forumposts fp中删除fp.id =(最后从上面的代码中选择),但这不起作用(我在“DELETE”或附近得到语法错误)。这是我第一次使用递归,我必须遗漏一些东西。任何帮助表示赞赏。
答案 0 :(得分: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中已删除的行从主表中删除。
编辑:对于9.1之前的PostgresSQL版本,您可以使用这样的初始查询:
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
);