MYSQL查找两个日期/时间之间的时间跨度

时间:2012-12-11 20:37:08

标签: mysql sql datetime

我有一个表有两个字段dt(DateTime)和isblocked(Bit)

enter image description here

我一直在努力寻找两个日期/时间之间的时间跨度,其中有45分钟连续免费 ​​- 基于开始日期/时间。

例如:基于上表使用2012-12-11 13:30:00'作为我的开始日期。 我需要这样的价值观:

2012-12-11 15:30:00
2012-12-11 16:45:00

我尝试了一些最小和最大查询,例如:

SELECT MIN(dt), isbooked
FROM booking
WHERE dt >= '2012-12-11 13:30:00' AND isbooked = 1
GROUP BY dt
LIMIT 1;

但我似乎无法将正确的结构放在一起。如果需要更多信息,请告诉我。

4 个答案:

答案 0 :(得分:2)

在MySQL中,您可以使用相关子查询执行此操作:

select min(b.dt) as StartTime, NotBookedTime as EndTime
from (select b.*,
             (select min(b2.dt) from booking b2 where b2.dt >= b.dt and b2.isbooked = 1
             ) as NotBookedTime
      from booking b
     ) b
where b.isbooked = 0
group by NotBookedTime
having date_add(min(b.dt), interval 45 minute) <=  NotBookedTime

这样做是为每条记录找到第一个预订的间隔,并记住时间。然后它找到第一个预定的间隔,并检查差异是45分钟或更长时间。

答案 1 :(得分:1)

这也应该有效:

SELECT d.dt
FROM (
  SELECT
    t1.dt,
    MIN(case when t2.isBooked then t2.dt end) AS next_booked,
    MAX(case when not t2.isBooked then t2.dt end) as max_unbooked
  FROM times t1 INNER JOIN times t2 ON t1.dt < t2.dt
  WHERE t1.isBooked =0
  GROUP BY t1.dt
) d
WHERE
  timediff(next_booked,d.dt)>='00:45:00' or
  (next_booked is null and timediff(max_unbooked,d.dt)>='00:30:00')

取决于你所追求的,它也可以简化为:

SELECT d.dt
FROM (
  SELECT
    t1.dt,
    MIN(t2.dt) as next_booked
  FROM times t1 left  JOIN times t2 ON t1.dt < t2.dt and t2.isBooked=1
  WHERE t1.isBooked =0
  GROUP BY t1.dt
) d
WHERE timediff(d.next_booked, d.dt)>='00:45:00'
      or d.next_booked is null
GROUP BY d.next_booked

答案 2 :(得分:0)

查看此SQLFiddle

SELECT min(b.dt) AS StartTime, NotBookedTime AS EndTime
FROM (SELECT b.*,
        (SELECT min(b2.dt) FROM DT b2 
           WHERE b2.dt >= b.dt AND b2.isBooked = 1
         ) AS NotBookedTime
     FROM DT b
    ) b
WHERE b.isBooked = 0
GROUP BY NotBookedTime
HAVING EndTime is not null

答案 3 :(得分:0)

您可以使用变量:

set @tp=now();
SELECT @tp:=dt as dt,isbooked FROM booking WHERE 
    dt >= addtime(@tp,'00:45:00') AND isbooked = 1
    ORDER BY dt;

其中@TP将获取所选上一个日期的值。