如何根据计算的列对mysql结果进行分组?

时间:2016-10-15 04:03:36

标签: mysql database

我正在尝试展示我网络上评论最多的帖子但是不可能.-。我一直都有这个mysql错误(无法对'comments'进行分组)

表之间的关系是:

table:post / colums:id_post,title,id_comment
table:comment / colums:id_comment,text,id_post

这是我正在尝试使用的查询

SELECT p.title AS title, COUNT(c.id_comment) AS comments
FROM post p
INNER JOIN comment c ON p.id_post=c.id_post
GROUP BY comments DESC

请为此选择或解决方案吗?

1 个答案:

答案 0 :(得分:0)

为什么要根据评论数量进行分组?您需要order by子句才能获得最多评论到顶部并按帖子分组:

SELECT p.title AS title, COUNT(c.id_comment) AS comments
FROM post p
INNER JOIN comment c ON p.id_post=c.id_post
GROUP BY p.id_post, p.title
ORDER BY comments DESC

您可能还希望获得limit条款,以便仅获得前N个评论帖子。