在mysql中显示所有日期,甚至没有数据

时间:2018-12-26 06:33:50

标签: mysql sql

我有一个查询

select value, updateddate from valid_table where date(updateddate) between '2018-11-01' and '2018-11-07';

value date
40    2018-11-01
50    2018-11-03
70    2018-11-05

但是我想显示所有日期,即使如下所示没有特定日期的数据,

value date
40    2018-11-01
0     2018-11-02
50    2018-11-03
0     2018-11-04
70    2018-11-05
0     2018-11-06
0     2018-11-07

注意:开始日期和结束日期可能在2018年10月1日和2018年12月1日

如何实现?

2 个答案:

答案 0 :(得分:0)

要获取开始日期和结束日期之间的日期,可以使用以下查询。希望这可以帮到你。要从表中获得此结果,可以使用联接。

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

答案 1 :(得分:0)

您可以在下面使用左联接尝试

 select tdate, coalesce(value,0) as value from 
    (select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) tdate from
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) t1
    left join valid_table on t1.tdate= updateddate 
    where tdate between '2012-02-10' and '2012-02-15'