I have a very simple MySQL table where I save highscores. It looks like that:

Id     Name     Score

So far so good. The question is: How do I get what's a users rank? For example, I have a users Name or Id and want to get his rank, where all rows are ordinal ordered descending for the Score.

An Example

Id  Name    Score
1   Ida     100
2   Boo     58
3   Lala    88
4   Bash    102
5   Assem   99

In this very case, Assem's rank would be 3, because he got the 3rd highest score.

The query should return one row, which contains (only) the required Rank.

link|improve this question
Your text/sample data does not clarify why type of ranking you want. Based on your accepted answer we assume you wanted Ordinal Ranking. See en.wikipedia.org/wiki/Ranking – Leigh Riffel Feb 22 at 22:54
@LeighRiffel Yes, exactly. – Michael Feb 22 at 22:58
feedback

3 Answers

up vote 2 down vote accepted
SELECT id, name, score, FIND_IN_SET( score, (
SELECT GROUP_CONCAT( score
ORDER BY score DESC ) 
FROM scores )
) AS rank
FROM scores

gives this list:

id name  score rank
1  Ida   100   2
2  Boo    58   5
3  Lala   88   4
4  Bash  102   1
5  Assem  99   3

Getting a single person score:

SELECT id, name, score, FIND_IN_SET( score, (    
SELECT GROUP_CONCAT( score
ORDER BY score DESC ) 
FROM scores )
) AS rank
FROM scores
WHERE name =  'Assem'

Gives this result:

id name score rank
5 Assem 99 3
link|improve this answer
How will this query behave if we have thousands (or millions) of rows in the table? – ypercube Feb 23 at 7:22
You'll have one scan to get the score list, and another scan or seek to do something useful with it. An index on the Score column would help performance on large tables. – cairnz Feb 23 at 8:02
The correlated (SELECT GROUP_CONCAT(score) FROM TheWholeTable) is not the best way. And it may have a problem with the size of the row created. – ypercube Feb 23 at 8:04
feedback
SELECT id, Name, 1+(SELECT count(*) from table_name a WHERE a.Score < b.Score) as RNK, Score
FROM table_name b;
link|improve this answer
feedback

One option would be to use USER variables:

SET @i=0;
SELECT id, name, score, @i:=@i+1 AS rank 
 FROM ranking 
 ORDER BY score DESC;
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.