I have a MySQL query that selects the players with the top 3 highest scores in my users table, then creates an extra column where their rank is assigned:
SELECT s.*, @curRank := @curRank + 1 AS rank
FROM users AS s
JOIN
( SELECT DISTINCT highscore
FROM users
ORDER BY highscore DESC
LIMIT 3
) AS lim
ON s.highscore = lim.highscore
, (SELECT @curRank := 0) r
ORDER BY s.highscore DESC ;
Current progress
So, if the table looked like this:
userid name highscore
0 sam 20
1 james 39
2 jack 10
3 harry 46
4 jennie 7
The result of the query would be this:
userid name highscore rank
3 harry 46 1
1 james 39 2
0 sam 20 3
Question
How could I alter this query so it also display's the user and their rank in the list of results? E.g. if $userName = "jenny", how could I return:
userid name highscore rank
3 harry 46 1
1 james 39 2
0 sam 20 3
4 jenny 7 5
Edit: I should mention - I am using MySQL version 5.0.96
解决方案
For versions prior to 8.0...
SELECT *
FROM
( SELECT a.*
, @i := @i+1 i
FROM my_table a
JOIN (SELECT @i:=0) vars
ORDER
BY highscore DESC
, userid
) x
WHERE name = 'jennie'
OR i <= 3
ORDER
BY i;