简体   繁体   English

MySQL检查时间范围是否超出一天的给定时隙

[英]MySQL Check if time range falls outside of given time slots for day

Let's say I have a bookings table: 假设我有一个预订表:

id|booking_ref|start_datetime      |end_datetime
-------------------------------------------------------
01|ABC        |2018-01-01 09:30:00 |2018-01-01 10:00:00
02|DEF        |2018-01-01 11:00:00 |2018-01-01 12:00:00
03|GHI        |2018-01-01 13:00:00 |2018-01-01 13:15:00

If I provide given time periods when these bookings are allowed to take place, how would I check if any bookings fall within the times when bookings aren't allowed? 如果我提供允许进行这些预订的给定时间段,我将如何检查是否有任何预订属于不允许预订的时间范围内?

For example allowed time slots are from: 例如,允许的时隙来自:

2018-01-01 09:00:00 to 2018-01-01 10:30:00
2018-01-01 11:00:00 to 2018-01-01 13:30:00
2018-01-01 14:00:00 to 2018-01-01 17:00:00

All of the bookings in the example table fall between the allowed time slots. 示例表中的所有预订都在允许的时隙之间。

How would you write a query to check if there are any bookings for a given day which doesn't fall into any of the allowed time periods? 您将如何编写查询以查询给定日期是否有未在任何允许的时间段内进行的预订?

I've tried the usual start_datetime >= and end_datetime <= etc. but can't figure it out. 我已经尝试了通常的start_datetime >=end_datetime <=等,但是无法弄清楚。

select * from bookings b
where exists (
    select 1 from disallowed d
    where b.start <= d.end and d.start <= b.end
);

One could also just hard-code those values: 一个人也可以硬编码这些值:

select * from bookings b
where b.start1 <= '2018-01-01 10:30:00' and '2018-01-01 09:00:00' <= b.end1
   or b.start1 <= '2018-01-01 10:30:00' and '2018-01-01 11:00:00' <= b.end1
   or b.start1 <= '2018-01-01 17:00:00' and '2018-01-01 14:00:00' <= b.end1;

Figured it out, this query will find any date ranges that fall outside of the given ranges in part or in whole. 弄清楚了,此查询将查找部分或全部超出给定范围的任何日期范围。 Hard-coded in the end. 最后硬编码。

SELECT
  *
FROM
  mi_bookings b
WHERE NOT (
    (b.start_datetime BETWEEN '2018-01-01 09:00:00' AND '2018-01-01 10:30:00') AND (b.end_datetime BETWEEN '2018-01-01 09:00:00' AND '2018-01-01 10:30:00')     
  OR 
    (b.start_datetime BETWEEN '2018-01-01 11:00:00' AND '2018-02-05 13:30:00') AND (b.end_datetime BETWEEN '2018-01-01 11:00:00' AND '2018-01-01 13:30:00')
  OR 
    (b.start_datetime BETWEEN '2018-01-01 14:00:00' AND '2018-01-01 17:00:00') AND (b.end_datetime BETWEEN '2018-01-01 14:00:00' AND '2018-01-01 17:00:00')
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM