如何获取mysql查询中的行的排名

时间:2014-11-14 11:15:20

标签: mysql

这是我的数据库结构

表:球员

id  | name      |  score
1   | Bob       |  600
2   | Alex      |  1400
3   | John      |  800
4   | sara      |  2000

我需要选择约翰的行并计算约翰排名的OrderBy得分

如你所见约翰排名第3(800),萨拉排名第1(2000),亚历克斯排名第2(1400)

Select @rownum := @rownum + 1 AS rank form players where id=3 OrderBy score

任何想法?

3 个答案:

答案 0 :(得分:1)

select rank
from
(
  Select id, name, @rownum := @rownum + 1 AS rank 
  from players 
  cross join (select @rownum := 0) r
  Order By score desc
) tmp
where id = 3

答案 1 :(得分:1)

您可以通过子查询来完成并计算得分超过certian id得分的玩家

Select count(*) as rank 
from players 
where score > (select score from players where id=3)

但是如果你想在排名旁边有其他信息,你可以通过

来完成
SELECT ranks . *
FROM (    
   SELECT @rownum := @rownum +1 ‘rank’, p.id, p.score
   FROM players p, (SELECT @rownum :=0)r
   ORDER BY score DESC
) ranks
WHERE id =3

答案 2 :(得分:0)

可能更容易进行自我加入,其中联合表得分更高(以获得得分更高的行)并且只计算: -

SELECT COUNT(*)
FROM players a
INNER JOIN players b
ON a.score >= b.score
WHERE a.id = 3

问题是如何处理相同的分数。