如何进行条件计数

时间:2019-06-22 16:22:42

标签: mysql sql

我有一个查询工作正常的表

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值,我该怎么做?

1 个答案:

答案 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

Demo for aggregations above