填充空日期

时间:2015-08-31 07:09:28

标签: mysql

我的数据库表结构类似于

stats_id stats_date   stats_visitors stats_visits
1        2015-08-01   10             20
2        2015-08-03   12             21
3        2015-08-04   14             24
4        2015-08-07   15             21

添加空状态日期的最简单方法是什么。例如,我错过了2015-08-02所以它应该是:

stats_id stats_date   stats_visitors stats_visits
1        2015-08-01   10             20
5        2015-08-02   0              0
2        2015-08-03   12             21
3        2015-08-04   14             24
6        2015-08-05   0              0
7        2015-08-06   0              0
4        2015-08-07   15             21

我可以检查每天是否有数据和填充,但是当我有超过10K行时,这不是一个好主意。如果我每天使用支票,我将生成超过10k的查询。

我能做到这一点吗?

2 个答案:

答案 0 :(得分:1)

这应该会帮助你。

insert into Table1 select '',selected_date,'0','0' 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 (select min(stats_date) from Table1) and (select max(stats_date) from Table1) and selected_date not in (select stats_date from Table1);

查询的select adddate部分会为您提供数据集最大和最小日期之间的所有日期,并使用not in我们只会获得数据中不存在的日期集。

由于你有自动递增id字段,你可以在select查询中传递一个空字符串,它会忽略它并插入自动递增的值。

选择所有日期查询的来源:How to get list of dates between two dates in mysql select query

希望这能解决你的问题。

答案 1 :(得分:0)

你可以试试这个;

insert into tbl(stats_date, stats_visitors, stats_visits)
select in_date, 0, 0
from (
    SELECT 
        @date := DATE_ADD(@date,INTERVAL 1 DAY) AS in_date
    from
        (SELECT @date := min(stats_date) from tbl) r CROSS JOIN
        (SELECT 0  UNION ALL SELECT 1  UNION ALL SELECT 2 UNION ALL SELECT 3) a CROSS JOIN  
        (SELECT 0  UNION ALL SELECT 1  UNION ALL SELECT 2 UNION ALL SELECT 3) b CROSS JOIN 
        (SELECT 0  UNION ALL SELECT 1  UNION ALL SELECT 2 UNION ALL SELECT 3) c CROSS JOIN 
        (SELECT 0  UNION ALL SELECT 1  UNION ALL SELECT 2 UNION ALL SELECT 3) d CROSS JOIN 
        (SELECT 0  UNION ALL SELECT 1  UNION ALL SELECT 2 UNION ALL SELECT 3) e
    where @date < (select max(stats_date) from tbl)
) t
where in_date not in (select stats_date from tbl);

此处子查询将提供min(stats_date)max(stats_date)之间的日期。

Cross join将提供最多1024行(即4 power 5
如果您的表格在1024之间的日期超过min and max date,那么请添加更多cross join或更多union all