I’ve got a list of items in my table, with fields votes_up and votes_down along with others. Now I want to order the items based on popularity which is a function of these two fields. The problem is that algorithm of popularity is dependent on the values of votes_up.
For example, if votes_up is greater 5:
popularity= (votes_up/votes_down)*20
If votes_up is greater than 50:
popularity= (votes_up/votes_down)*15
(I’ve just used this to explain.. the actual algorithm is different).
Now how can I do this, because normally I would do in my query something like this:
ORDER BY (votes_up/votes_down)*20)
But I cannot do this right now because what comes after ORDER BY is dependent on the value of votes_up. Only way I can do this is by:
if(votes_up >5){
p = (votes_up/votes_down)*20;
} else if(votes_up > 50){
p = (votes_up/votes_down)*15;
}
Then in my query I can have ORDER BY p.
Now of course this is not valid PHP, but I just want to explain my problem. I hope you understand what I want to achieve.
You could simply calculate your popularity using a case statement and then order based on that. It might look like this:
You never stated what do do with votes_up <= 5 so I just put a
?for that case, you can fill in the blank.Note however that this will not be able to utilize an index for this sort, so if you have large numbers of rows you expect to return, your query might perform slowly.
You might want to consider adding a field into the table that stores the calculated popularity value (which would by updated by the application on votes up or down). You could then index this field and get a more optimized sort.