SELECT
DATE_FORMAT(uploadTime_beg, "%Y-%m-%d") as time,
SUM(field01) as sumStatus1,
SUM(field02) as sumStatus2,
SUM(field03) as sumStatus3,
SUM(field04) as sumStatus4,
SUM(field05) as sumStatus5
FROM
health_realdata
WHERE DATE_FORMAT(uploadTime_beg,'%Y%u') = DATE_FORMAT(CURDATE(),'%Y%u')
GROUP BY DATE_FORMAT(uploadTime_beg,"%Y-%m-%d");
這個SQL查出的數據如下:
![圖片說明](http://img.ask.csdn.net/upload/201511/24/1448359276_377950.png)
我想要的效果是:雖然數據庫中沒有2015-11-25的數據,但是也要查出來,只是後面的值顯示為0.
請問在MYSQL中如何實現,上面的SQL如何修改呢。
我看到網上說需要一個日歷輔助表,說的不是很詳細,我試了一下好像有問題,
如果這種方法可行,還請大牛們寫詳細點,謝謝。
思路:
1、將你上邊查詢出來的結果跟你說的那個有從2015-11-01 到2015-11-30的日歷輔助表進行右連接查詢
2、將1中查詢出的結果進行再次的查詢處理,將null值更換為0;
下邊的為代碼示意,沒有進行調試,應該會有問題,大體結構是這樣的:
SELECT o.time,
case when o.sumStatus1 is null then 0 else o.sumStatus1 end as sumStatus1,
case when o.sumStatus2 is null then 0 else o.sumStatus2 end as sumStatus2,
case when o.sumStatus3 is null then 0 else o.sumStatus3 end as sumStatus3,
case when o.sumStatus4 is null then 0 else o.sumStatus4 end as sumStatus4,
case when o.sumStatus5 is null then 0 else o.sumStatus5 end as sumStatus5
(
(
SELECT
DATE_FORMAT(uploadTime_beg, "%Y-%m-%d") as time,
SUM(field01) as sumStatus1,
SUM(field02) as sumStatus2,
SUM(field03) as sumStatus3,
SUM(field04) as sumStatus4,
SUM(field05) as sumStatus5
FROM
health_realdata
WHERE DATE_FORMAT(uploadTime_beg,'%Y%u') = DATE_FORMAT(CURDATE(),'%Y%u')
GROUP BY DATE_FORMAT(uploadTime_beg,"%Y-%m-%d");
) as a
right join 表d on a.time = d.time
) o