Hello all,
I am working with polls: Each poll has many options and users can vote in polls once. Thus I have a 'votes' table with the following fields:
- id (id of the vote)
- option_id (id of the poll option chosen)
- user_id (id of the user)
- poll_id (id of the poll)
So here is what I'm trying to do: Given an array of poll_ids, I want to have a query return the most voted on option for each poll. Thus if I give poll_id's of 1 & 2, I want to get back the most voted on options for polls 1 & 2. I have tried the following:
SELECT
t1.poll_id,
t1.option_id,
count(t1.option_id) AS num_votes,
t2.option_id AS user_vote
FROM
votes AS t1
JOIN
votes AS t2
ON
t1.id = t2.id
WHERE
t1.poll_id IN (30,40)
GROUP BY
t1.option_id;
That almost does the trick...but gives me all poll options with corresponding votes for each poll provided, not just the most voted option. If anyone has any ideas, I'd really appreciate it. Thanks.