如何创建递归 CTE 查询来获取根parent_id SQL

问题描述 投票:0回答:1

我有一张这样的桌子

发帖

id: text pk not null
content: text not null
author_id: text fk references User(id) not null
parent_id: text fk references Post(id)

我的问题是,如何在 Postgres 中获取从子帖子(通过使用其 id)到根帖子(其中parent_id 为空)的每个帖子?

sql postgresql recursive-query
1个回答
0
投票

我能够通过这个查询做到这一点

使用递归parent_posts(id,parent_id,内容,author_id)AS( 从“帖子”中选择 id、parent_id、内容、author_id c WHERE id = 'b71fe331-12a0-4383-bb12-bff505db4016' 联合所有 选择 p.id、p.parent_id、p.content、p.author_id 来自parent_posts po,“帖子”p 其中 p.id = po.parent_id ) 从parent_posts中选择*

© www.soinside.com 2019 - 2024. All rights reserved.