查询以检查给定的日期范围是否不适合多个日期范围

Query to check if a given range of date doesn't fits between multiple range of dates

我有一个包含 2 列的 table,checkinDate 和 checkoutDate。我要做的是在 table 中添加一个范围,前提是它不与其他范围重叠。我如何知道给定的日期范围是否适合查询的所有这些范围?

例如,来自以下行:

startDate   -   endDate
2019-12-10  -   2019-12-15
2019-12-16  -   2019-12-22
2019-12-29  -   2019-01-05
2020-01-20  -   2020-01-25

如果给定的日期范围从 2019-12-232019-12-28,则不会重叠其他范围所以我可以将它添加到 table.

但是如果范围从2019-12-232019-12-30,它重叠了一个范围所以我无法将其添加到 table.

我知道如何逐行检查范围,但不知道如何检查整个范围 table。

好吧,如果它们重叠,则给定范围的任一边界都在 table 的范围内。所以你可以使用类似的东西:

SELECT *
       FROM elbat
       WHERE '2019-12-23' > startdate
             AND '2019-12-23' < enddate
              OR '2019-12-28' > startdate
                 AND '2019-12-28' < enddate;

这是检查插入查询中日期重叠的简单方法

insert into mytable(startDate, endDate)
select i.startDate, i.endDate
from (select '2019-12-23' startDate, '2019-12-30' endDate) i
where not exists (
    select 1 
    from mytable t 
    where t.startDate <= i.endDate and t.endDate >= i.startDate
)

要插入的日期范围在别名为 i 的子查询中声明。如果 table 中的任何记录与该范围重叠,则跳过插入,否则它发生。

Demo on DB Fiddle:

-- set up
CREATE TABLE mytable(
   id int auto_increment primary key
   ,startDate DATE  NOT NULL 
  ,endDate   DATE  NOT NULL
);
INSERT INTO mytable(startDate,endDate) VALUES ('2019-12-10','2019-12-15');
INSERT INTO mytable(startDate,endDate) VALUES ('2019-12-16','2019-12-22');
INSERT INTO mytable(startDate,endDate) VALUES ('2019-12-29','2019-01-05');
INSERT INTO mytable(startDate,endDate) VALUES ('2020-01-20','2020-01-25');

-- initial table content
select * from mytable order by startDate
id | startDate  | endDate   
-: | :--------- | :---------
 1 | 2019-12-10 | 2019-12-15
 2 | 2019-12-16 | 2019-12-22
 3 | 2019-12-29 | 2019-01-05
 4 | 2020-01-20 | 2020-01-25
-- this range does not overlap
insert into mytable(startDate, endDate)
select i.startDate, i.endDate
from (select '2019-12-23' startDate, '2019-12-30' endDate) i
where not exists (
    select 1 
    from mytable t 
    where t.startDate <= i.endDate and t.endDate >= i.startDate
)

-- confirm it was inserted
select * from mytable order by id
id | startDate  | endDate   
-: | :--------- | :---------
 1 | 2019-12-10 | 2019-12-15
 2 | 2019-12-16 | 2019-12-22
 3 | 2019-12-29 | 2019-01-05
 4 | 2020-01-20 | 2020-01-25
 5 | 2019-12-23 | 2019-12-30
-- this range overlaps
insert into mytable(startDate, endDate)
select i.startDate, i.endDate
from (select '2019-12-23' startDate, '2019-12-28' endDate) i
where not exists (
    select 1 
    from mytable t 
    where t.startDate <= i.endDate and t.endDate >= i.startDate
)

-- it was not inserted
select * from mytable order by id
id | startDate  | endDate   
-: | :--------- | :---------
 1 | 2019-12-10 | 2019-12-15
 2 | 2019-12-16 | 2019-12-22
 3 | 2019-12-29 | 2019-01-05
 4 | 2020-01-20 | 2020-01-25
 5 | 2019-12-23 | 2019-12-30