I am working on a sever app that has multiple games and should be able to handle millions of players. Each game needs a leaderboard and must be able to show the player's current position and top 10 players, as well as the positions of the players friends.
Currently I am using two tables.
user_score
- id
- user_id
- game_id
- score
- created_at
user_ max_score
- id
- user_id
- game_id
- max_score
- created_at
- updated_at
Whenever a user plays any game for the first time data is inserted in the first and second table. If the user plays a second time and scores more than their previous score we insert data into user_score table and update user_max_score table with the new max_score.
And for getting the rank of the user I fire query like this.
SET @i=0;
SELECT id, user_id, max_score, @i:=@i+1 AS rank
FROM user_max_score WHERE game_id = $gameId
ORDER BY max_score DESC, updated_at ASC;
Is there any better approach than this?