patternsqlMajor
Get the rank of a user in a score table
Viewed 0 times
therankuserscoregettable
Problem
I have a very simple MySQL table where I save highscores. It looks like that:
So far so good. The question is: How do I get what's a users rank?
For example, I have a users
An Example
In this very case,
The query should return one row, which contains (only) the required Rank.
Id Name ScoreSo 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 99In 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.
Solution
SELECT id, name, score, FIND_IN_SET( score, (
SELECT GROUP_CONCAT( score
ORDER BY score DESC )
FROM scores )
) AS rank
FROM scoresgives 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 3Getting 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 3You'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.Code Snippets
SELECT id, name, score, FIND_IN_SET( score, (
SELECT GROUP_CONCAT( score
ORDER BY score DESC )
FROM scores )
) AS rank
FROM scoresid name score rank
1 Ida 100 2
2 Boo 58 5
3 Lala 88 4
4 Bash 102 1
5 Assem 99 3SELECT id, name, score, FIND_IN_SET( score, (
SELECT GROUP_CONCAT( score
ORDER BY score DESC )
FROM scores )
) AS rank
FROM scores
WHERE name = 'Assem'id name score rank
5 Assem 99 3Context
StackExchange Database Administrators Q#13703, answer score: 44
Revisions (0)
No revisions yet.