2012-11-08 47 views
1

我有這樣如果沒有記錄,我可以如何計數爲0?

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

我需要這樣的

temp t 
A1  1 
A2  0 
A3  0 
+0

你必須有一個不同的表,它具有所有類型的'臨時',像A1,A2 .. 我的意思是 哪張表是你想要得到A1,A2,A3 –

+1

你正在比較字符串'NULL'而不是記錄列爲NULL的地方 - 這是故意的嗎? – Bridge

回答

1

O/P你將不得不做一些自我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的索引。

相關問題