2016-01-05 146 views
0

我想有一個MySQL查詢,給定一個指定的日期,它將返回最後7天的結果,但在MySQL表中可能有空白。MySQL查詢,添加空白填補空白

所以該表可能看起來像這樣

tblMyData

TestDate | val1 | val2 
2014-07-10 | 20  | 30 
2014-07-09 | 10  | 10 
2014-07-07 | 11  | 22 
2014-07-04 | 9  | 45 

但是我的查詢需要填補空白,所以我的結果是這樣的

TestDate | val1 | val2 
2014-07-10 | 20  | 30 
2014-07-09 | 10  | 10 
2014-07-08 | 0  | 0  <<-- Added by the query 
2014-07-07 | 11  | 22 
2014-07-06 | 0  | 0  <<-- Added by the query 
2014-07-05 | 0  | 0  <<-- Added by the query 
2014-07-04 | 9  | 45 

任何想法如何我可以做這個?

回答

2

一種解決方案是使用子查詢生成日期,然後將此子查詢與您的表聯接。

如果你只需要在過去的7天,然後你可以用這個嘗試:

select d.testdate, coalesce(t.val1,0), coalesce(t.val2,0) 
from 
    (select current_date as testdate 
    union all select current_date - interval 1 day 
    union all select current_date - interval 2 day 
    union all select current_date - interval 3 day 
    union all select current_date - interval 4 day 
    union all select current_date - interval 5 day 
    union all select current_date - interval 6 day) d 
    left join tblMyData t 
    on d.testdate = t.testdate 

如果不是的CURRENT_DATE,你想要的最後7天的表,那麼你的查詢可以是這樣的:

select m.m - interval d day, coalesce(t.val1,0), coalesce(t.val2,0) 
from 
    (select max(testdate) as m from tblMyData) m 
    cross join 
    (select 0 as d 
    union all select 1 
    union all select 2 
    union all select 3 
    union all select 4 
    union all select 5 
    union all select 6) d 
    left join tblMyData t 
    on m.m - interval d day = t.testdate 

請看小提琴here

+0

有關用一組日期填充子查詢的另一種方法(在上面的答案中用別名「d」),請參閱此文章:http://stackoverflow.com/questions/9295616/how-to - 獲得一覽的-日期,兩日期,在MySQL的選查詢間。如果您可能的日期範圍遠遠超過7天,這可能是需要的。 – Nate

0

如果你可以使用SEQUENCE ENGINE,你可以這樣做。 此示例爲最近100天,但您可以更改它。

INSERT IGNORE INTO tblMyData 
SELECT DATE(now() - INTERVAL seq DAY),0,0 FROM seq_0_to_100;