0

我有一个评论表。每一条评论都可能是对另一条评论的回应。

表结构:

CREATE TABLE comments
(
    id integer NOT NULL,
    content text,
    root integer NULL,
    date_added timestamp without time zone DEFAULT now()
)

我需要选择最新的 10 个线程及其响应,因此结果我可能有例如 10 个线程和 8 个响应。我不确定这样做是不是很热。我试过了:

SELECT content FROM comments 
ORDER BY date_added DESC 
LIMIT 10 + (SELECT COUNT(*) FROM COMMENTS WHERE root IS NOT NULL)

但这没有适当的效果。

4

1 回答 1

1

不确定这是您想要的,但看起来递归 cte 可以帮助您:

with recursive cte as (
    -- anchor of the query - last 10 threads
    select c.id, c.content 
    from comments as c
    where c.root is null -- top level threads
    order by c.date_added desc
    limit 10

    union all

    -- recursively get all children
    select c.id, c.content
    from comments as c
        inner join cte as cr on cr.id = c.root
)
select
    content
from cte
于 2013-11-13T18:22:40.037 回答