简体   繁体   中英

How to count votes in mySQL tables?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM