简体   繁体   English

MySQL不重叠日期范围

[英]MySQL get NOT overlapping date ranges

I have seen so many questions similar to this, but they all seem to be tailored to highlighting when date ranges are overlapping, I need the opposite. 我已经看到了很多与此类似的问题,但是当日期范围重叠时,它们似乎都是为了突出显示而设计的,我需要相反的选择。

Lets say I have a table like so 可以说我有这样的桌子

id| start_date | end_date   | room_id
1 | 15/05/2018 | 30/06/2020 | 1
2 | 01/11/2018 | 31/10/2019 | 2
3 | 01/08/2020 | 31/07/2022 | 1
4 | 01/12/2019 | 30/11/2021 | 2
5 | 01/08/2020 | 31/07/2022 | 3

As you can see there are multiple bookings for each room. 如您所见,每个房间都有多个预订。 I need to be able to specify either a single start/end date or both, and get back what DOESN'T overlap (ie, the available rooms) 我需要能够指定一个开始/结束日期或同时指定两者,然后取回不重叠的内容(即可用的房间)

For example, if i specified just a start date of 01/05/2018 then every room will return, or if i specify just an end date of 30/07/2020 then every room will return because neither of those dates are between the start and end date of each booking. 例如,如果我仅指定开始日期为01/05/2018,那么每个房间都将返回,或者如果我仅指定结束日期为30/07/2020,则每个房间都将返回,因为这些日期都不在开始之间和每次预订的结束日期。 Even though id 1 has a booking that ends on 30/06/2020 and a new one that starts on 01/08/2020, it would still be available because someone could book between those 2 dates. 即使id 1的预订终止于2020年6月30日,新的预订开始于01/08/2020,该预订仍将可用,因为有人可以在这2个日期之间进行预订。

If I specified both start and end dates, it searches through and returns only the rooms that have no bookings between the 2 dates at all. 如果我同时指定了开始日期和结束日期,它将搜索并仅返回两个日期之间没有预订的房间。

I have read plenty of questions online and the logic seems to be 我在网上读了很多问题,逻辑似乎是

SELECT *
FROM bookings
WHERE $start_date < expiry_date AND $end_date > start_date

which i understand, but if I ran this query above with the following dates 我理解的,但是如果我在上面的查询中使用以下日期

SELECT *
FROM bookings
WHERE '2018-10-01' < expiry_date AND '2019-10-01' > start_date

it returns 它返回

id| start_date | end_date   | room_id
1 | 15/05/2018 | 30/06/2020 | 1
2 | 01/11/2018 | 31/10/2019 | 2

How do I get it so that when I pass either a start date, end date or BOTH it returns the rooms that are available? 我如何获得它,以便当我传递开始日期,结束日期或两者时都返回可用的房间?

By De Morgan's Laws, we can negate the overlapping range query you gave as follows: 根据De Morgan的定律,我们可以对您提供的重叠范围查询取反,如下所示:

SELECT *
FROM bookings
WHERE $start_date >= expiry_date OR $end_date <= start_date;

The expression ~(P ^ Q) is equivalent to ~PV ~Q . 表达式~(P ^ Q)等效于~PV ~Q

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

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