Fof*_*ole 3 postgresql recursive-query sql-delete
我有以下sql让我所有的根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
Run Code Online (Sandbox Code Playgroud)
我想要删除选中的记录.像从forumposts fp中删除的东西,其中fp.id =(最后从上面的代码中选择),但这不起作用(我在"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);
Run Code Online (Sandbox Code Playgroud)
其他可能的组合,例如根据子表中已删除的行从主表中删除,请查看文档.
编辑:对于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
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4208 次 |
| 最近记录: |