简体   繁体   中英

How can I sort rows by number of corresponding rows in different table?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM