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

标签 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

最佳答案

编辑: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)

fiddle : 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);

fiddle : http://sqlfiddle.com/#!2/ab1c3/2/0

(出于说明目的,我添加了一些额外的示例数据)

关于mysql - 循环遍历mysql表以查找表中缺失的一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25098311/

相关文章:

php - 防止同时访问数据库表行

sql - 是否可以在数据库中找到所有具有系统生成名称的主键?

sql - 为什么在我的更新 sql 查询中会影响不同的值?

mysql - 完全盲目的SQL注入(inject)列枚举?

mysql - 为什么我使用 GROUP BY 时我的 MySQL 结果不正确?

mysql - 自动递增插入MYSQL表中间

php - 如何防止 PHP 中的 SQL 注入(inject)?

sql - 选择每个人在其他表中有多少文档

sql - 根据日期连接表

PHP 和 MySql 查询