Select 特定玩家的排名 sql 查询
Select rank of a specific player sql query
我正在尝试进行查询,我已经在 stackof 上搜索了答案,但没有找到符合我需要的答案。
我有一个名为 table 的播放器,其中有两列,"nickname" 和 "score"。
我使用此查询来获取前 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')
但他们总是 return 4 为 "jiji" 或 "ciao",这是最后一个在 table 中得分为 20 的玩家的排名。
如何才能让 "jiji" 获得 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';
使用常用定义,jiji
的 排名 将是:
SELECT count(*) + 1 AS rank
FROM player
WHERE score > (SELECT score FROM player WHERE nickname = 'jiji');
这个returns“2”,因为score = 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');
我正在尝试进行查询,我已经在 stackof 上搜索了答案,但没有找到符合我需要的答案。 我有一个名为 table 的播放器,其中有两列,"nickname" 和 "score"。 我使用此查询来获取前 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')
但他们总是 return 4 为 "jiji" 或 "ciao",这是最后一个在 table 中得分为 20 的玩家的排名。
如何才能让 "jiji" 获得 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';
使用常用定义,jiji
的 排名 将是:
SELECT count(*) + 1 AS rank
FROM player
WHERE score > (SELECT score FROM player WHERE nickname = 'jiji');
这个returns“2”,因为score = 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');