I have a situation where I need to retrieve the position of the current user in a regional leaderboard.
My tables look something like this:
Users
id | city | ...
Collected_Items
id | user_id | value | ...
Achievements
id | user_id | value | ...
So simply put, I'd like to retrieve the position in the leaderboard and the sum of the value
of each collected_item
as well as the sum of the value
each achievement
. Equal total values can be either ranked equally or based on the timestamp of collection (first to collect wins)
I have this so far: (adapted from this SO answer)
SELECT
user_id,
user_points
FROM (
SELECT
user_id,
SUM(collected_items.value) AS 'user_points'
FROM collected_items
GROUP BY user_id
ORDER BY SUM(collected_items.value) DESC
) AS T1
GROUP BY T1.user_points
ORDER BY T1.user_points DESC
Which produces results like
Results
user_id | user_points
2 | 61
1 | 1
Which is great, however I need to include the achievements, get the position of each user and also query by users.city
(users only view leaderboards within their own city)
My ideal results would look like this:
Results
rank | user_id | value
How would I alter the above to produce the desired results? (I'm open to using PHP manipulation also)
Notes (for speed purposes):
- There are 101 collectable items
- There are 101 achievements
- There will be up to 250,000 users