I have a users
table and a scores
table:
-------- users Name | Type ------------------------|---------------- uuid | VARCHAR(36) name | VARCHAR(255) ... | ...
-------- scores Name | Type ------------------------|---------------- uuid | VARCHAR(36) user_uuid | VARCHAR(36) score | INT(11)
I can fetch a user
, including their total score
using a subquery like this:
SELECT user.uuid, user.name,
(SELECT SUM(score) FROM scores WHERE user_uuid = user.uuid) AS score
FROM user WHERE user.uuid = [USER_UUID];
But now, how can I fetch the user's rank? That is, rank being determined by their score vs the scores of every other user.
Is it really necessary to loop through every single user
, calculate all of their scores, and then order their scores to determine the rank of one single user? Performing this query on the fly seems taxing, especially if I have a large number of users. Should I instead build a separate rankings
table, and re-sort the table after each INSERT into the scores
table? That doesn't seem ideal either.
I have another application which will require on-the-fly ranking as well, but the calculations are much more severe: a user's score
is determined by a complex algorithm spanning at least 5 different tables. So I really need some insight on database ranking in general - although the above problem is an easy way to represent it. What are some good practices to consider?