我正在为我们的小组项目实施排行榜。
这是我查询用于计算表中用户ID 2的状态数的查询。
$query = "SELECT COUNT(content) FROM status WHERE userid=2 ";
现在,我如何查询具有最多状态的用户ID?
示例表
|| content || userid ||
|| x || 1 ||
|| xx || 1 ||
|| y || 2 ||
|| yy || 2 ||
|| yyy || 2 ||
|| z || 3 ||
结果
1st = 2 with 3 status
2nd = 1 with 2 status
3rd = 3 with 1 status
我将如何限制结果?如果我只需要前5名呢?
与此问题相关
我想在用户表中添加另一列(number_of_status)而不是这个多个查询...哪个更好?
谢谢!
答案 0 :(得分:1)
应该可以使用GROUP BY
:
SELECT userid, COUNT(*) AS status_count
FROM status
GROUP BY userid
ORDER BY status_count DESC
LIMIT 5
答案 1 :(得分:0)
您可以使用GROUP BY查询和LIMIT来实现此目的。
SELECT userid, COUNT(content) as statuses
FROM status
GROUP BY userid
ORDER BY statuses DESC
LIMIT 5