PostgreSQL在查询中检查父级的父级

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

好的,我会尽量精确。我有一个注释数据库,其中注释具有parent_comment_id。我想从该表中选择一些注释,并为这些注释选择相应数量的答案。这是我的问题:如果我随意选择评论,我可能会抓住一些没有答案的人。但是,如果我先选择评论答案,那么我可能会抓住已经是另一个评论答案的答案。因此,我想做的是抢占答案,这些答案是对注释的立即答案(parent_comment_id = NULL),然后基于parent_comment_id获得这些注释。我将如何处理查询?

假设此数据库布局

comment_id    parent_comment_id
1             NULL
2             NULL
3             1
4             3
5             1
6             3
7             1
8             4
9             NULL
10            NULL
...

现在,我选择两个答案和相应的注释。如果仅选择前2个答案,则得到注释3和4,但是如果回溯它们,则仅得到注释1,因为注释4是对答案的回答。相反,我只想查找其父注释没有父注释的注释,在此示例中为注释3和5。

我还没有真正尝试过任何方法,因为意识到如果不以某种方式递归地获取我不知道如何在SQL查询中做父母的父母,它是行不通的。

sql database postgresql join recursive-query
2个回答
0
投票

我用一个非常简单的方法解决了它。可能是可怕的做法,但适用于我的用例^^

对于给定的示例,将是这样的:

select distinct on (parent_comment_id) c.id, c.parent_comment_id, c.text
from comments c
where parent_comment_id is not null
and (select parent_comment_id from comments p where id = c.parent_comment_id) is null

0
投票

我只想查找其父注释没有父注释的注释。

我认为您只需要自联接和一些过滤:

select c.*
from comments c
inner join comments pc on pc.comment_id = c.parent_comment_id
where pc.parent_comment_id is null

您也可以使用exists

select c.*
from comments c
where exists (
    select 1 
    from comments pc 
    where pc.comment_id = c.parent_comment_id and pc.parent_comment_id is null
)
© www.soinside.com 2019 - 2024. All rights reserved.