如何使用in作为子查询将表中的不存在值计为0

时间:2018-03-23 05:47:50

标签: mysql

我需要帮助来编写正确的查询。我们有一个调查数据库,其中我们有一个问题的OfferedAnswers表,其中包含question_id和answer_id的映射。

OfferedAnswers:

-----------------------
answer_id   | question_id
-----------------------
1           |  1
-----------------------
2           |  1
-----------------------
3           |  1
-----------------------
4           |  1
-----------------------

另一个是FeedbackQuestionAnswer表,它记录了用户投票的question_id和answer_id的响应。

FeedbackQuestionAnswer:

-----------------------
question_id   | answer_id
-----------------------
1             |  1
-----------------------
1             |  2
-----------------------
1             |  1
-----------------------


 select    FeedbackQuestionAnswer.answer_Id, 
           count(FeedbackQuestionAnswer.answer_Id) as count 
           from dEbill.FeedbackQuestionAnswer  
           where FeedbackQuestionAnswer.answer_Id in
           (select answer_Id 
                   from dEbill.OfferedAnswers 
                   where question_Id = 1)
           group by FeedbackQuestionAnswer.answer_Id

在上述情况下,输出为:

    -----------------------
    answer_id   | count
    -----------------------
    1           |  2
    -----------------------
    2           |  1
    -----------------------

而我想:

    -----------------------
    answer_id   | count
    -----------------------
    1           |  2
    -----------------------
    2           |  1
    -----------------------
    3           |  0
    -----------------------
    4           |  0
    -----------------------

我尝试使用OfferedAnswer.answer_Id而不是FeedbackQuestionAnswer.answer_Id但是出现了范围错误。 我也试过加入但没有成功。

1 个答案:

答案 0 :(得分:3)

只需使用左连接,并计算第二个表中的非NULL条目:

SELECT
    t1.answer_id,
    COUNT(t2.answer_id) AS count
FROM OfferedAnswers t1
LEFT JOIN FeedbackQuestionAnswer t2
    ON t1.answer_id = t2.answer_id
WHERE
    t1.question_id = 1
GROUP BY
    t1.answer_id
ORDER BY
    t1.answer_id;

screen capture of query output

Demo