您好我想做以下事情:
SELECT * FROM tbl_article
JOIN tbl_comments ON tbl_article.id = tbl_comments.article_id
ORDER BY COUNT(tbl_comments.article_id)
有人可以建议我如何让它发挥作用吗?
答案 0 :(得分:4)
这应该做的工作:
SELECT
tbl_article.*, COUNT(tbl_comments.article_id) as total_comments
FROM
tbl_article
LEFT JOIN
tbl_comments ON tbl_comments.article_id = tbl_article.id
GROUP BY
tbl_article.id
ORDER BY
COUNT(tbl_comments.article_id)
答案 1 :(得分:1)
SELECT * FROM
(
SELECT tbl_article.id, COUNT(tbl_comments.id) AS CommentCount FROM tbl_article
LEFT OUTER JOIN tbl_comments ON tbl_article.id = tbl_comments.article_id
GROUP BY tbl_article.id
) ra
ORDER BY CommentCount DESC
编辑:我更改了连接类型。无论在评论表中是否有相应的条目,都应该出现文章。我们现在也正在对文章表中的id字段进行分组。