I have a leaderboard which has a "score" column. I also have an index on the score column which allows me to order the table by score very quickly, even slicing out the top ten or any number of scores - even with 5 million rows!
However, what I would really like is to also display the players "rank" in the leaderboard. I have tried a few methods but none seem to stack up when dealing with anything over 100000 rows (they start taking over half a second, which is too long considering I'm expecting hundreds of cuncurrent users).
I'm currently using the following query to determin one users rank, then simlpy incrementing up for the users above this in my output - but it's very slow.
SELECT tro.score, tro.userId,
(
SELECT count(*)
FROM scoreboard tri
WHERE tri.score >= :score
) AS rank
FROM test_tracks tro
WHERE userId = :userID");
I am thinking of generating a ranking table to "cache" the users rank whenever they insert a new score into the scoreboard, but even generating this will take a LONG time (minutes, possibly hours).
Does anyone know of any good guides or tricks to establishing rankings? Preferably I'd like to be able to pageinate the results too, but even just establishing rank for the moment would be sufficient!
Thanks in advance!
The best way to do this is to use a table that is updated on a regular basis (once an hour, once a day etc) by a schedule that can take a longer query and run it. There isn't any need to smash the database all the time with those sorts of heavy queries. It also means that the long-running query is run once a while, not with every user that browses through o that page.
A perfect example is here on SO, where the weekly/monthly/yearly totals are updated once per day.