我有以下 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
问题是我希望删除选定的记录。类似于 delete from forumposts fp where fp.id=(last select from the code above) 但这不起作用(我在“DELETE”处或附近收到语法错误)。这是我第一次使用递归,我一定遗漏了一些东西。感谢您的帮助。
最佳答案
您可以简单地使用 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
);
关于postgresql - 删除递归 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10381243/