在分数表中获取用户的排名

时间:2014-05-26 15:04:22

标签: mysql sql ranking

我有一个简单的MySQL表,我保存了游戏的分数。它看起来像是:

**Id  -  UserId  -  Score**

问题是:我如何获得用户排名?我有一个用户ID

示例

**Id - UserId - Score**

1 - AAAA - 150

2 - BBBB - 110

3 - BBBB - 120

4 - CCCC - 102

5 - AAAA - 130

在这种情况下,IdUser CCCC排名将是3,因为他获得了第3高分。

查询应返回一行,其中包含(仅)所需的Rank。

谢谢!

1 个答案:

答案 0 :(得分:3)

如果您有用户ID,则需要返回分数相同或更高的用户数。

select count(*) as `rank`
from table t join
     (select score from table t where userId = @USERID) var
     on t.score >= var.score;

如果你有重复的分数,你可能真的想要:

select 1 + count(*) as `rank`
from table t join
     (select score from table t where userId = @USERID) var
     on t.score > var.score;

目前还不清楚重复用户需要什么。我可能会建议:

select 1 + count(*) as `rank`
from (select userId, max(score) as score
      from table t
      group by userId
     ) t join
     (select max(score) from table t where userId = @USERID) var
     on t.score > var.score;