MySQL- 查找周期重叠的记录

MySQL- Find records with overlapping period

我有一个tablehotel_booking

reference start_date numberOfDays
ABC 11-08-2021 2
DEF 12-08-2021 2
GHI 13-08-2021 3
JKL 10-08-2021 2

所以我想要的第一个任务是获取所有开始日期在 x 和 y 日期之间的预订,这是直接查询

select reference
from hotel_booking
where DATE(start_date) BETWEEN '2021-08-11' AND '2021-08-12'

这个returns我的ABC和DEF简直完美。

现在我想根据 numberOfdays

检查所有具有重叠时段的预订

例如,根据 numberOfDays

获取 startDate 和 endDate 提到的时间段内的所有预订

INPUT: 例如,如果开始日期为 11-08-2021,结束日期为 12-08-2021,则

预期输出:返回的预订是 JKL、ABC 和 DEF,因为 JKL 预订了 2 天,这将与 startDate 11-08-2021

重叠

任何指针将不胜感激

由于您没有保存结束日期,因此您需要将其计算为 start_date + interval numberOfDays days 以获得唯一的结束日期。日期重叠查询如下所示:

SELECT *
FROM t
WHERE @d2 > start_date AND (start_date + interval numberOfDays day) > @d1
-- In order to check [2021-08-11, 2021-08-12]
-- You will set @d1 and @d2 to 2021-08-11 and 2021-08-13

为了完整起见,这里是包含结束日期的版本:

SELECT *
FROM t
WHERE @d2 >= start_date AND (start_date + interval numberOfDays - 1 day) >= @d1
-- In order to check [2021-08-11, 2021-08-12]
-- You will set @d1 and @d2 to 2021-08-11 and 2021-08-12