Reputation: 11
I'm making a small-scale reddit clone. There is a table for posts, a table for comments (relevant only for context), and a table for posts_comments. I'm trying to sort posts by the number of comments the post has.
This is the init for the posts_comments table
CREATE TABLE posts_comments (
id SERIAL PRIMARY KEY,
parent_id INTEGER,
comment_id INTEGER,
post_id INTEGER
)
This is the call I have, but it doesn't seem right
SELECT * FROM posts p
JOIN posts_comments pc ON p.id = pc.post_id
ORDER BY (SELECT COUNT(*) FROM pc WHERE pc.post_id = p.id) DESC
LIMIT $1
OFFSET $2
I want the output to be a list of posts sorted by the number of comments linked to that post
Upvotes: 1
Views: 28
Reputation: 12432
maybe like this:
SELECT
COUNT(pc.post_id) OVER (PARTITION BY p.id) AS num_comments
,* FROM posts p
LEFT OUTER JOIN posts_comments pc ON p.id = pc.post_id
ORDER BY 1 DESC
LIMIT $1
OFFSET $2
of it you only want the list of posts and not the comments.
SELECT
COUNT(pc.post_id) AS num_comments
,p.* FROM posts p
LEFT OUTER JOIN posts_comments pc ON p.id = pc.post_id
GROUP BY p.id
ORDER BY 1 DESC
LIMIT $1
OFFSET $2
Upvotes: 1