Skip to content
Advertisement

Calculating rank in PHP/MySQL

I’ve got a table in MySQL lets just say for example its got two fields Username, GameName and Score. I want to calculate the rank of a user for an indivudal game name so I could do the query

JavaScript

to get a list of all users in order of highest to lowest and assign a number to each user.

But is there an easier way to get the rank for an indivdual user rather than selecting the entire table as that doesn’t seem too efficient.

Thanks

Advertisement

Answer

If you want overall rankings, you unfortunately have to sort the whole table. Simply put, you cannot know someone’s rank in the table without knowing the other ranks in the table.

That said, if you are worried about performance, there’s a fairly easily solution here – cache the result of your ranking query (maybe into another a MySQL table!), and query that for all your reads. When someone posts a new score, recalculate your temporary table. You can periodically flush all records under a certain rank (say, anyone ranking under 100 gets removed from the scores table) to keep recomputations fast, since nobody would ever climb in rank after being knocked down by a higher score.

JavaScript

Then, whenever you want to read a rank for a game:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement