如何获取MySQL中2个给定字段之间间隔的TIME

时间:2013-06-19 13:19:06

标签: mysql sql gaps-and-islands

我必须关注表格,其中start_timeend_timeTIME字段:

 ____________________________________
| id | day | start_time |  end_time  |
|____|_____|____________|____________|
|  1 | 1   |    8:00    |    12:00   |

我想获得start_timeend_time之间每隔60分钟的开始时间,因为:

 _______
| start |
|_______|
|  8:00 |
|  9:00 |
| 10:00 |
| 11:00 |

这可能吗?感谢

1 个答案:

答案 0 :(得分:1)

如果你有一个包含整数的表,这会更容易。如果该字段是日期时间,您可以这样做(最多7小时):

select date_add(t.start_time, interval n.n hour)
from t join
     (select 0 as n union all select 1 union all select 2 union all select 3 union all
      select 4 union all select 5 union all select 6 union all select 7
     ) n
     on date_add(t.start_time, interval n.n hour) <= t.end_time

使用time,你可以通过转换为秒并在那里进行算术来实现:

select sec_to_time((floor(time_to_sec(t.start_time - 1)/3600)+1) + n.n*3600)
from t join
     (select 0 as n union all select 1 union all select 2 union all select 3 union all
      select 4 union all select 5 union all select 6 union all select 7
     ) n
     on (floor(time_to_sec(t.start_time - 1)/3600)+1) + n.n*3600 <= t.end_time