排名MySQL查询结果

时间:2016-01-25 17:30:13

标签: php mysql

我有一张这样的表:

name | score
asdf | 50
zxcv | 100
qwer | 80
aaa  | 70
.
.
.

我可以通过此查询获得某人的排名:

SELECT(
SELECT COUNT(*)
FROM leaderboard m2
WHERE m2.score >= m1.score
) as rank,name,score
FROM leaderboard m1
WHERE name='aaa'

这个查询会给我这样的东西:

rank | name | score
  3  | aaa  |  70

问题是我希望看到的结果名称=' aaa'是这样的:

rank | name | score
  2  | qwer |  80
  3  | aaa  |  70
  4  | asdf |  50

(以及aaa&#39的排名和aaa&#39的结果)

怎么可能呢?

1 个答案:

答案 0 :(得分:0)

我对这个问题的自我结论:

SELECT( SELECT COUNT(*) FROM leaderboard m2 WHERE m2.score >= m1.score ) as rank,name,score FROM leaderboard m1 WHERE (SELECT ( SELECT COUNT(*) FROM leaderboard m2 WHERE m2.score >= m1.score ) as rank )>=( SELECT( SELECT COUNT(*) FROM leaderboard m2 WHERE m2.score >= m1.score ) as rank FROM leaderboard m1 WHERE name = 'AAA' ) - 5 ORDER BY rank LIMIT 0,10