我有这样的问题
select `temp`, IfNULL(count(id),0) t
from survey
where `temp`<>'NULL' and `temp`<> '' and date(submitdate)='date'
group by `temp
有 o/p
temp t
A1 1
但如果没有记录,则在所选日期会发生以下情况:我没有得到任何结果。答案像 A1,A2,A3
我需要这样的o/p
temp t
A1 1
A2 0
A3 0
最佳答案
您将不得不使用一些自JOIN
技巧来获取每个答案的记录:
SELECT s.`temp`, count(survey.id) t
-- This will ensure that you will get all relevant answers A1, A2, A3
FROM (
SELECT DISTINCT `temp`
FROM survey
WHERE `temp` <> 'NULL' and `temp` <> ''
-- ^^^^^^^^^ Might want to replace this by `temp` IS NOT NULL?
) s
-- Only then, you will actually get the actual records per answer and date
LEFT OUTER JOIN survey
ON s.`temp` = survey.`temp`
AND date(survey.submitdate) = 'date'
GROUP BY s.`temp`
请确保您在 survey.temp
上有一个索引。
关于mysql - 如果没有记录,我怎么能算作 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13288777/