我有一个查询工作正常的表
SELECT answers.answer,answers.id,answers.user_id,COUNT(vote.vote)
FROM user_answers AS answers
LEFT JOIN user_answer_vote AS vote ON answers.id =vote.answer_id
WHERE answers.question_id = $question_id
GROUP BY answers.id ORDER BY COUNT(vote.vote) DESC
查询将按预期返回,但问题是vote.vote列同时具有-eve和+ eve值,我希望它仅计算+ eve值,我该怎么做?
答案 0 :(得分:2)
使用case..when
语句
COUNT(case when vote.vote='+eve' then 1 end)
在查询内
SELECT a.answer,a.id,a.user_id,
COUNT(case when v.vote='+eve' then 1 end)
-- SUM(v.vote='+eve') might be another alternative for the above COUNT
FROM user_answers AS a
LEFT JOIN user_answer_vote AS v
ON a.id =v.answer_id
WHERE a.question_id = $question_id
GROUP BY a.id
ORDER BY COUNT(case when vote.vote='+eve' then 1 end) DESC
-- SUM(v.vote='+eve') might be another alternative for the above COUNT
编辑(根据您的评论):
SELECT a.answer,a.id,a.user_id,
SUM(case when v.vote='+eve' then 1 else -1 end )
FROM user_answers AS a
LEFT JOIN user_answer_vote AS v
ON a.id =v.answer_id
WHERE a.question_id = $question_id
GROUP BY a.id
ORDER BY SUM(case when v.vote='+eve' then 1 else -1 end ) DESC