Reputation: 5220
I have the following mySQL tables:
Answers
+-----------+-----------+---------+-------------+---------------+ | answer_id | content | user_id | question_id | timestamp | +-----------+-----------+---------+-------------+---------------+ | 66 | Blah blah | 101 | 33 | 23/12/13 4:13 | | 67 | Thank you | 102 | 34 | 23/12/13 12:11| +-----------+-----------+---------+-------------+---------------+
Votes
+-----------+---------+-----------+ | direction | user_id | answer_id | +-----------+---------+-----------+ | 1 | 101 | 66 | | 0 | 102 | 66 | | 1 | 100 | 66 | | 1 | 103 | 66 | | 0 | 101 | 67 | +-----------+---------+-----------+
What I want to do is to select all answers with their respective vote, like so and ORDER BY vote
+-----------+------+ | answer_id | vote | +-----------+------+ | 66 | 2 | | 67 | -1 | +-----------+------+
So far, I've got:
SELECT answers.answer_id,votes.direction,COUNT(*) AS answer_vote
FROM answers
LEFT JOIN votes ON answers.answer_id=votes.answer_id
WHERE
answers.question_id='61'
GROUP BY votes.direction
I'm quite stumped.
Upvotes: 1
Views: 718
Reputation: 21522
Try that:
SELECT answers.answer_id,SUM(IF(votes.direction = 0, -1, 1)) AS answer_vote
FROM answers
LEFT JOIN votes ON answers.answer_id=votes.answer_id
WHERE
answers.question_id='61'
GROUP BY answers.answer_id
Upvotes: 4