选择变量LIMIT值

时间:2013-11-13 15:11:03

标签: sql postgresql

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

表格结构:

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)

但这没有适当的效果。

1 个答案:

答案 0 :(得分: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