1

我有一个users包含每个用户信息的表格。然后是包含posts文章信息的表格user_posts,最后是包含以下列的表格:

user_id
post_id
...

我正在尝试获取帖子数量最多的用户图表。我做了这个查询:

SELECT u.id as uid, u.name as uname, count(up.id) as up_count FROM users as u JOIN user_posts as up ON up.user_id = u.id ORDER BY vcount DESC LIMIT 25

这个查询只返回一个用户和表中所有行的总数user_posts

我究竟做错了什么?我需要按发布每个用户的文章数排序 25 个用户的列表。

先感谢您

4

2 回答 2

3

您的查询需要有GROUP BY子句,因为您使用了COUNT()函数。

SELECT   u.id as uid, 
         u.name as uname, 
         count(up.id) as up_count 
FROM     users as u 
           LEFT JOIN user_posts as up  
              ON up.user_id = u.id 
GROUP BY u.id, u.name
ORDER BY up_count DESC LIMIT 25

您必须将它们分组,ID否则您将对所有记录进行单一的总计数结果。还有一件事,使用LEFT JOIN这样即使没有帖子的用户仍然会在你的结果中可见,分数为0.

于 2012-09-04T22:42:38.050 回答
1
SELECT 
    u.id as uid, u.name as uname, count(up.id) as up_count 
FROM users as u 
    JOIN user_posts as up ON up.user_id = u.id 
GROUP BY 
    u.id, u.name
ORDER BY 
    vcount 
DESC LIMIT 25
于 2012-09-04T22:42:23.367 回答