基本上,
我有两张表,一张有一些帖子,另一个用于评论,我想做的是创建一个包含最受欢迎帖子的页面,我将根据评论的数量呈现热门帖子。
这是我到目前为止的查询
mysql_query("SELECT * FROM posts JOIN comments ON posts.id = comments.content_id ORDER BY count('comments.id') LIMIT 10");
但是 count() 搞砸了,有人可以帮我吗?谢谢!
如果你有一个聚合函数,比如COUNT(*)
,你应该包含一个GROUP BY
子句:
此外,由于您想要返回评论最多的帖子,因此您需要按降序(从高到低)对数量进行排序。
SELECT
posts.id,
COUNT(comments.content_id) as post_comments
FROM
posts
LEFT JOIN comments
ON posts.id = comments.content_id
GROUP BY posts.id
ORDER BY post_comments DESC
LIMIT 10
删除comments.id 周围的引号:) 我还添加了我认为缺少的组。
mysql_query("SELECT * FROM posts JOIN comments ON posts.id = comments.content_id GROUP BY posts.id ORDER BY count(comments.id) LIMIT 10");
从 count 语句中删除引号并添加一个组:
SELECT * FROM posts
JOIN comments ON posts.id = comments.content_id
GROUP BY comments.content_id
ORDER BY count(comments.content_id)
LIMIT 10