循环遍历mysql表以查找表中缺少的一天

时间:2014-08-02 18:47:39

标签: mysql sql

我正在将csv文件上传到mysql表中。

time_stamp,"Phase 1","Phase 2","Phase 3",Total
2014-07-09 07:59:21,8345,8665,5461,22471
2014-07-09 08:59:21,8345,8665,5461,22471
2014-07-10 07:59:57,9349,9750,6550,25649

我想运行一个循环来检查两个时间段之间是否存在时间戳,例如7:59:59和8:59:59,它应该将前一个时间戳的值附加到表中

2014-07-09 08:29:21,8345,8665,5461,22471

1 个答案:

答案 0 :(得分:1)

编辑:解决方案差距为30分钟:

select timestampadd(minute, 30, x.time_stamp) as time_stamp,
       x.phase_1,
       x.phase_2,
       x.phase_3,
       x.total
  from tbl x
 cross join tbl y
 where y.time_stamp =
       (select max(z.time_stamp)
          from tbl z
         where timestampdiff(minute, z.time_stamp, x.time_stamp) < 30)
   and timestampdiff(minute, y.time_stamp, x.time_stamp) not between 0 and
       29.99
   and y.time_stamp < (select max(time_stamp) from tbl)

小提琴: http://sqlfiddle.com/#!2/51d84/3/0

解决1天的差距:

insert into tbl
select timestampadd(day, 1, x.time_stamp) as time_stamp,
       x.phase_1,
       x.phase_2,
       x.phase_3,
       x.total
  from tbl x
 cross join tbl y
 where y.time_stamp =
       (select max(z.time_stamp)
          from tbl z
         where cast(z.time_stamp as date) < cast(x.time_stamp as date))
   and cast(y.time_stamp as date) < cast(x.time_stamp as date)
   and cast(timestampadd(day, 1, x.time_stamp) as date) not in
       (select cast(time_stamp as date) from tbl);

小提琴: http://sqlfiddle.com/#!2/ab1c3/2/0

(为了说明目的,我添加了一些额外的样本数据)