我正在查询几个表来获取每个答案的计数,当结果表中找到记录时,此查询正常工作。我想以这样一种方式处理这个查询:如果在结果表中没有找到任何答案或问题的记录,它必须显示该值的计数'0'及其各自的问题和答案。我必须在此查询中进行哪些更改?或者有什么办法,请告诉我?提前谢谢。
这是我的查询。
SELECT s.NAME AS surveyname,
COUNT(r.answer_id) AS totalAnswer,
q.id AS questionid,
q.question AS question,
a.answer AS answer,
COUNT(r.textbox) AS totalTextbox,
COUNT(r.textboxmulti) AS totalTextboxmulti,
qt.template AS template,
s.NAME AS surveyname,
COUNT(r.other) AS other
FROM surveys s
INNER JOIN survey_results AS sr
ON s.id = sr.survey_id
INNER JOIN results AS r
ON sr.id = r.surveyresults_id
INNER JOIN questions AS q
ON r.question_id = q.id
INNER JOIN questiontypes AS qt
ON q.questiontype_id = qt.id
LEFT JOIN answers AS a
ON r.answer_id = a.id
WHERE s.id = < cfqueryparam cfsqltype = "cf_sql_integer" value = "#arguments.surveyid#" >
GROUP BY q.id,
a.id
ORDER BY q.id, a.id a.rank
如果找不到匹配的记录,则应显示如下所示的内容。
surveyname totalanswer qid question answer totaltextbox totaltextboxmulti template totalother
somename 0 1 what ? yes 0 0 multiple 0
somename 0 1 what ? no 0 0 multiple 0
如果有匹配的记录,那么它应该在totalanswer或totaltextbox等中显示计数。
答案 0 :(得分:0)
尝试添加此COUNT(ifnull(r.other,0)) AS other
SELECT s.NAME AS surveyname,
COUNT(r.answer_id) AS totalAnswer,
q.id AS questionid,
q.question AS question,
a.answer AS answer,
COUNT(r.textbox) AS totalTextbox,
COUNT(r.textboxmulti) AS totalTextboxmulti,
qt.template AS template,
s.NAME AS surveyname,
COUNT(ifnull(r.other,0)) AS other
FROM surveys s
INNER JOIN survey_results AS sr
ON s.id = sr.survey_id
INNER JOIN results AS r
ON sr.id = r.surveyresults_id
INNER JOIN questions AS q
ON r.question_id = q.id
INNER JOIN questiontypes AS qt
ON q.questiontype_id = qt.id
LEFT JOIN answers AS a
ON r.answer_id = a.id
WHERE s.id = < cfqueryparam cfsqltype = "cf_sql_integer" value = "#arguments.surveyid#" >
GROUP BY q.id,
a.id
ORDER BY a.rank
修改
同样@SlowCoder建议,尝试在结果表上使用LEFT JOIN
。