如何计算连接语句

时间:2011-09-29 10:16:21

标签: mysql

我有桌子postint post_id, varchar title, text content
和表commentint comment_id, int post_id, varchar content其中post_id是外键引用表格。

如何通过评论计数获得每个帖子订单的post_id和评论总和。谢谢。

1 个答案:

答案 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