我有桌子post
:int post_id, varchar title, text content
和表comment
:int comment_id, int post_id, varchar content
其中post_id是外键引用表格。
如何通过评论计数获得每个帖子订单的post_id和评论总和。谢谢。
答案 0 :(得分:6)
如果您想要没有评论的帖子:
SELECT
post.post_id,
--post.title,
--post.content,
COUNT(comment.post_id) AS comment_count
FROM post
LEFT JOIN comment ON post.post_id = comment.post_id
GROUP BY post.post_id
ORDER BY comment_count DESC
(此查询使用MySQL GROUP BY with hidden columns扩展名。)
如果您不想要没有评论的帖子,可以使用更简单的查询:
SELECT post_id, COUNT(*) AS comment_count
FROM comment
GROUP BY post_id
ORDER BY comment_count DESC