简体   繁体   中英

how to order data in mysql by join count?

I have two tables :

posts : id,title,content,show,created_at

comments: id,post_id,created_at

I'm trying to order posts by most commented.

SELECT *, COUNT(comments.id) AS total_comments
FROM comments LEFT JOIN posts ON posts.id = comments.post_id
WHERE posts.show = '1'
GROUP BY complains.id
ORDER BY total_comments DESC

The problem is that the posts with 0 comments don't appear. Any help would be much appreciated.

With your join above, you are incorrectly joining to get commens that have posts You should have done a right join or swap the tables in left join like below.

Select *, COUNT(comments.id) as total_comments
FROM posts
LEFT outer JOIN comments on  posts.id = comments.post_id
WHERE posts.show = '1'
GROUP BY posts.id
ORDER BY total_comments DESC

You need to do a RIGHT JOIN instead of a LEFT JOIN. Or swap the tables in the LEFT JOIN clause.

While there are many ways to solve this, I think this code is easy to read and understand.

The query in the LEFT JOIN can be copied out and run on its own to help debug. Then you join that result set to the posts table and order the results.

SELECT p.*, IFNULL(c.total_comments, 0) as total_comments
FROM posts p
LEFT JOIN (select post_id, count(post_id) as total_comments from comments group by post_id) as c ON p.id = c.post_id
WHERE p.show = '1'
ORDER BY c.total_comments DESC

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