views:

214

answers:

2

I am working with a MySQL database version 5.0.41 (and PHP 5.2.6, though that may not be relevant to this question).

I have a table called votes with the following fields: id, item_id, vote_value. Each time a user on the site submits a positive vote for an item, a new row is created with the corresponding item_id and a positive number (i.e. 1). When the vote is negative, a row is created with the corresponding item_id and a negative number (i.e. -1). I'd like to select, with one query (if possible), the item_id that has the most votes. To do this, I first need to sum up all the votes for each individual item_id (to get a number like 38 or -14) and then select the maximum for that number. I am not sure how to write the query for that.

Could you help?

Thanks!

+1  A: 

You could do something like:

SELECT item_id, SUM(vote_value) AS total, COUNT(id) AS c
FROM votes
GROUP BY item_id
ORDER BY total DESC, c DESC
LIMIT 1
VoteyDisciple
thanks! what is the purpose of selecting the count of id (i.e. COUNT(id))?
yuval
MAX should be SUM, and you should also select the item_id
Zed
I misread your original question thinking that "number of votes" was a tiebreaker if the `SUM` was the same. If the number of votes is irrelevant, the `COUNT` serves no purpose in this query.
VoteyDisciple
+3  A: 
SELECT item_id, SUM(vote_value) AS sum
FROM votes
GROUP BY item_id
ORDER BY sum DESC
LIMIT 1
Zed
thank you!! what is the purpose of the GROUP BY clause here?
yuval
I think I figured it out. Without the GROUP BY clause, the sql will simply select the highest sum of votes regardless of the item_id (regardless of which item the votes belong to). So if I have 20 votes for one word and 40 for another, instead of the max sum showing up as 40, it will show up as 60 - since it's not grouping the votes by anything.Thanks!
yuval
Yep!
Zed