2010-12-01 38 views
2

我試圖報告我們每天所做的採訪次數。按日期計算並按組返回0沒有值

所以我有采訪的表 如

interviewid,STAFFID是,迄今爲止,評論...

,幷包含從2005年迄今的所有具有單日期字段的日期參考表至2020年名爲ref。

我的查詢是:

SELECT count(*) as cnt FROM `interviews` 
right JOIN `dateRef` ON `date` = ref where type = 2 
and date > date_sub(now(),interval 7 day) group by date_format(ref,'%Y-%m-%d') 

是工作正常顯示的採訪,我們沒有,但不是當我們沒有做任何採訪......

例如,這將返回:

1 
2 
4 

但它應該返回

0 
1 
0 
2 
0 
4 
0 

編輯:

顯然,問題來自where子句,因爲如果我刪除,查詢工作正常...

回答

3

嘗試更換到

right join 

代替

left join 

另一個變化是

where type = 2 

where type = 2 OR type IS NULL 

所以最終的查詢

SELECT count(*) as cnt FROM `interviews` 
right JOIN `dateRef` ON `date` = ref where (type = 2 OR type is null) 
and date > date_sub(now(),interval 7 day) group by date_format(ref,'%Y-%m-%d') 
+0

我有完全相同的結果 – 2010-12-01 09:05:05

+0

已更新的答案,請參閱 – 2010-12-01 09:27:51

0

如果我理解正確的話,type是面試的一列。由於您使用的是正確的連接,因此您的連接表中包含日期不連續的行,但這些行的type(以及interviews的任何其他列)中有NULL,因爲interviews表中沒有這些日期的條目。它們被WHERE子句過濾掉,該子句需要type=2,這就是爲什麼COUNT看不到它們。

您可能會嘗試類似WHERE (type=2 OR type IS NULL),至少如果interviews.type從不NULL