假设我有一张预订表:
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
如果我提供允许进行这些预订的特定时间段,我如何检查预订是否属于不允许预订的时间?
例如,允许的时间段来自:
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
示例表中的所有预订都介于允许的时间段之间。
您如何编写查询以检查某一天是否有任何预订不属于任何允许的时间段?
我尝试了通常的start_datetime >=
和end_datetime <=
等,但无法理解。
答案 0 :(得分:1)
select * from bookings b
where exists (
select 1 from disallowed d
where b.start <= d.end and d.start <= b.end
);
还可以对这些值进行硬编码:
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;
答案 1 :(得分:0)
想出来,这个查询将找到部分或全部超出给定范围的任何日期范围。最后硬编码。
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')
)