0

I have a comments table. Every single comment could be a response to another comment.

Table structure:

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

I need to select the newest 10 threads with their responses, so in result I may have for example 10 threads and 8 responses. I'm not sure hot to do that. I've tried:

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

But this has no proper effect.

2
  • simple example of input data and desired output data could help. Do you need all responses down to the tree? Commented Nov 13, 2013 at 15:22
  • Yes, I need whole tree limited to 10 by threads. Commented Nov 13, 2013 at 15:29

1 Answer 1

1

not sure is that what you want, but looks like recursive cte could help you:

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
Sign up to request clarification or add additional context in comments.

1 Comment

This is pretty what I need. As far I know using LIMIT with UNION requires brackets added at start and end of queries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.