So here is my problem, I am working on a wait listing system for an app. A user would sign up to be notified when we launch, and offer referral links to help "boost" their spot in the wait list.
The problem I am having is how should I rank them inside of a MySQL or NoSQL database. The issue I am running into is this, if my database looks like this:
User | Ranking | Invited
-------------------------
user1 | 1 | 0
user2 | 2 | 0
user3 | 3 | 0
user4 | 4 | 0
user5 | 5 | 0
user6 | 6 | 0
user7 | 7 | 0
user8 | 8 | 1
Now, assuming user8 now invites 1 friend. They get bumped up to the top, but how do I go about sorting this data? It is fine reordering the entire table to look like this:
User | Ranking | Invited
-------------------------
user1 | 2 | 0
user2 | 3 | 0
user3 | 4 | 0
user4 | 5 | 0
user5 | 6 | 0
user6 | 7 | 0
user7 | 8 | 0
user8 | 1 | 1
But not very practical if the records go over a few hundred. Maybe I am not looking at this problem the right way? There must be a simpler solution? Any pointers or help is appreciated! Thank you.
If you want the ranking to be based on who has invited the most people, and if the same number of invites, their original rank, just sort that way when you read the table:
select user from waitlisttable order by invited desc, ranking;
If you need that order in some larger query, you could create a view for that, but actually updating the rankings for all existing records should definitely be avoided.
If you want to get the "rank" for all the users, see How to show sequential number in MySQL query result.
If you really need to be able to look up a single user's rank, then you probably do need to update all the rows; depending on how heavy your load is, you would either do so every X minutes by some job, or each time a row is updated via a trigger. A simple example of doing the former would be:
set @rank:=0;
update waitlisttable set ranking=(@rank:=@rank+1) order by invitations desc, initial_ranking;