MySQL order by count of another table
Let's say I have:
SELECT bloggers.*,
开发者_如何学运维 COUNT(post_id) AS post_count
FROM bloggers
LEFT JOIN blogger_posts ON bloggers.blogger_id = blogger_posts.blogger_id
GROUP BY bloggers.blogger_id
ORDER BY post_count
That returns all bloggers ordered by their post count. What if I want just some bloggers but still ordered by the same criteria (for example those whose AUX field is equal to 3)?
The WHERE
clause should come immediately before the GROUP BY
clause. When in doubt about something as straightforward as syntax, the place to look is the manual.
MySQL Manual :: SELECT Syntax
SELECT bloggers.*,
COUNT(post_id) AS post_count
FROM bloggers
LEFT JOIN blogger_posts ON bloggers.blogger_id = blogger_posts.blogger_id
WHERE bloggers.AUX = 3
GROUP BY bloggers.blogger_id
ORDER BY post_count
精彩评论