HI,
我昨天实际上发布了类似(或相同?)的问题,但我认为我需要发布一个新问题,因为我有一个简短而明确的问题.
我有下表.
id point
1 30
2 30
3 29
4 27
5 28
6 26
Run Code Online (Sandbox Code Playgroud)
我想要的是:
让所有用户按排名排序.用户#1和#2应该有1作为他们的排名值,因为他们都有30分
我想按用户ID查询排名.当我查询用户#1和#2时,我喜欢得到1作为我的排名的结果,因为他们都有30分
添加于:3/18
我尝试了Logan的查询,但得到了以下结果
id point rank
1 30 1
2 30 1
3 29 3
4 27 5
5 28 4
6 26 6
Run Code Online (Sandbox Code Playgroud)
只需计算有多少人的积分比他们多。
select count(1) from users
where point > (select point from users where id = 2) group by point
Run Code Online (Sandbox Code Playgroud)
这将为您提供给定用户拥有更多积分的人数。因此,对于用户 1 和用户 2,结果将为 0(零),这意味着他们是第一个。
您推荐的子查询方法将按比例缩放. http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/显示了一种更有效的用户变量方法.以下是对您的问题的未经测试的改编:
@points := -1; // Should be an impossible value.
@num := 0;
SELECT id
, points
, @num := if(@points = points, @num, @num + 1) as point_rank
, @points := points as dummy
FROM `users`
ORDER BY points desc, id asc;
Run Code Online (Sandbox Code Playgroud)