Saturday, May 8, 2010

Retrieving player's ranking in MySQL

Here's a neat little trick I figured out for myself when I was coding in MySQL. How to retrieve a player's current rank in a Leaderboards sort-of table.

-- this will calculate our current rank
SELECT count(DISTINCT exp) AS rank FROM player WHERE (exp > $exp);

-- this will retrieve 3 players that are of greater rank than us
SELECT * FROM player WHERE (exp > $exp) ORDER BY exp, username ASC LIMIT 3

-- this will retrieve 3 players that are of lower rank than us (or equal rank)
SELECT * FROM player WHERE (exp <= $exp) && (username != '$username') ORDER BY exp DESC LIMIT 3

-- top ten players
SELECT * FROM player ORDER BY exp DESC LIMIT 10

My example code comes from a PHP environment so $exp is a variable storing the selected player's current experience points, which in this example determines his rank. The greater one's experience points, the greater his rank. $username is a variable storing the selected player's unique username.

No comments:

Post a Comment

Made me post. 0/10.