如何统计mySQL表中的投票?

时间:2013-12-23 07:46:41

标签: mysql

我有以下mySQL表:

答案

+-----------+-----------+---------+-------------+---------------+
| 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|
+-----------+-----------+---------+-------------+---------------+

投票

+-----------+---------+-----------+
| direction | user_id | answer_id | 
+-----------+---------+-----------+
|         1 |     101 |        66 |
|         0 |     102 |        66 |
|         1 |     100 |        66 |
|         1 |     103 |        66 |
|         0 |     101 |        67 |
+-----------+---------+-----------+

我想做的是选择所有答案并进行各自的投票,如此和ORDER BY投票

+-----------+------+
| answer_id | vote |
+-----------+------+
|        66 |    2 |
|        67 |    -1 |
+-----------+------+

到目前为止,我已经:

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

我很难过。

1 个答案:

答案 0 :(得分:4)

试试:

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