Reputation: 1482
There is a platform on which we rank users based on their points. Let's say there are about 10,000 entries. And database looks something like below.
Id | UserName | Points | Rank |
---|---|---|---|
0 | Archit | 0 | 4 |
1 | Archit1 | 15 | 1 |
2 | Archit2 | 10 | 2 |
3 | Archit3 | 5 | 3 |
Whenever somebody does an action their point increases or decreases, based on that I also need to update the Rank in the database. But the problem is that updating it, again and again, every time somebody does action is a very slow process. And also calculating the rank while showing it on the profile is also not a good way.
What should be the ideal solution to such a problem?
Upvotes: 1
Views: 188
Reputation: 2327
To make it efficient you should change only ranks changed, and not recalculate the whole data every time.
As you haven't specified programming language, here is an example pseudo code:
-- input variables: CurrID, PointChange
CurrRank = Rank[CurrID]
Points[CurrID] = Points[CurrID] + PointChange
CurrPoints = Points[CurrID]
NewRank = SELECT count(Id) From YourTable where Points >= CurrPoints
if NewRank > CurrRank Then
update YourTable Rank = Rank - 1 where Rank > CurrRank And Rank <= NewRank
else
update YourTable Rank = Rank + 1 where Rank <= CurrRank And Rank > NewRank
end if
Rank[CurrID] = newRank
Upvotes: 1