In SQL or GQL or JDOQL, how can I query for the row that has the highest value in 2 columns (that have the lowest difference)?

StackOverflow https://stackoverflow.com/questions/5023832

Question

Say for example I have a table:

Table: Message
| data | likes | dislikes |

How can I efficiently find the row that has the highest number of likes and dislikes i.e. most controversial. So for the following example:

{("Hello", 10, 5)
("Ola!", 5, 5)
("Ni Hao!", 2, 2)
("Wazzup!", 5, 7)}

"Hello" would be chosen.

Any help would be highly appreciated!

Was it helpful?

Solution

1) You might want to use some other metrics instead of abs(likes - dislikes). In this case, (0, 5) and (100, 105) will be equally controversial.
I think, likes*dislikes might work in your conditions.

2) I'm not sure about jdoql, but since you specified sql tag, in standard sql this can be done without sorting. Something like

select * from Message 
    where likes*dislikes = (select max(likes*dislikes) from Message)

OTHER TIPS

GQL (assuming you're using the app engine datastore) won't be able to do a query on a calculation.

You would need to add another property to your model (eg called 'controversy'), and calculate it every time you change the number of likes or dislikes. Then you could do a simple query on that other property (ie in descending order, then fetch the first N records).

select top 1 (likes+dislikes ) as sumOfLikesDislikes from Message 
order by sumOfLikesDislikes desc

As suggested by Nikita, you can use (likes*dislikes) as LikesTimesDislikes (for metrics) if you want.

You can even do both :

select top 1 (likes+dislikes ) as sumOfLikesDislikes, 
             (likes*dislikes ) as LikesTimesDislikes  
from Message 
order by sumOfLikesDislikes desc, LikesTimesDislikes   desc

(First by sum, then by metrics)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top