选择特定播放器sql查询的排名

时间:2016-11-02 18:41:39

标签: mysql sql ranking

我试图进行查询,我已经在stackof上搜索了一个答案,但没有找到符合我需求的答案。 我有一个名为player的表,其中有两列,"昵称"和"得分"。 我使用此查询来获得前5名玩家:

SELECT nickname, score
FROM player 
ORDER BY score DESC LIMIT 5; 

我得到了这个答案:

nickname - score:    
zod      - 30  
ciao     - 20  
jiji     - 20  
mayina   - 20      
jon      - 0. 

现在,我想拥有一个单一玩家的等级,让我们说" jiji"结果得到3,因为它是列表中的第三个结果。

我尝试了许多查询,例如

SELECT COUNT(*) AS rank 
FROM player
WHERE score >= (SELECT score FROM player WHERE nickname = 'jiji')

但他们总是返回4,#14; jiji"或者" ciao",这是在该表中得分为20的最后一位玩家的等级。

我怎样才能获得3" jiji"而不是?非常感谢你。

2 个答案:

答案 0 :(得分:3)

试试这个:

SET @rank=0;
SELECT * 
FROM (SELECT @rank:=@rank+1, nickname, score 
    FROM player 
    ORDER BY score 
    DESC) AS t
WHERE t.nickname = 'jiji';

在得分关系的情况下纠正关于此不稳定的评论。为了使其稳定,我们可以将分类更改为基于分数,然后是昵称:

SELECT * 
FROM (SELECT @rank:=@rank+1, nickname, score 
    FROM player 
    ORDER BY score, nickname 
    DESC) AS t
WHERE t.nickname = 'jiji';

答案 1 :(得分:1)

使用常用定义,jiji等级将是:

SELECT count(*) + 1 AS rank 
FROM player
WHERE score > (SELECT score FROM player WHERE nickname = 'jiji');

返回“2”,因为得分= 30时会有联系。

如果您希望排名稳定且每行不同,则需要一个额外的密钥。一个明显的关键(在这种情况下)是nickname

SELECT count(*)  AS rank 
FROM player p CROSS JOIN
     (SELECT score FROM player WHERE nickname = 'jiji') s
WHERE p.score > s.score or
      (p.score = s.score and p.nickname <= 'jiji');