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

问题描述 投票:2回答:2

我有一个包含2列的表格,checkinDate和checkoutDate。我要做的是仅在表中不与其他范围重叠的情况下添加该范围。如何通过查询知道给定的日期范围是否适合所有这些范围?

例如,从以下各行:

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,则不会与其他范围重叠,因此我可以将其添加到表中。

但是如果范围从2019-12-232019-12-30,则它与一个范围重叠,因此我无法在表中添加它。

我知道如何逐行检查范围,但不知道如何用整个表格对其进行检查。

mysql sql database date date-range
2个回答
0
投票

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

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的子查询中声明。如果表中的任何记录与该范围重叠,则会跳过插入,否则会发生。

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 |结束日期-:| :--------- | :---------1 | 2019-12-10 | 2019-12-152 | 2019-12-16 | 2019-12-223 | 2019-12-29 | 2019-01-054 | 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 |结束日期-:| :--------- | :---------1 | 2019-12-10 | 2019-12-152 | 2019-12-16 | 2019-12-223 | 2019-12-29 | 2019-01-054 | 2020-01-20 | 2020-01-255 | 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 |结束日期-:| :--------- | :---------1 | 2019-12-10 | 2019-12-152 | 2019-12-16 | 2019-12-223 | 2019-12-29 | 2019-01-054 | 2020-01-20 | 2020-01-255 | 2019-12-23 | 2019-12-30

0
投票

如果它们重叠在给定范围的边界上,则在表中的范围内。因此,您可以使用以下方式:

SELECT *
       FROM elbat
       WHERE '2019-12-23' > startdate
             AND '2019-12-23' < enddate
              OR '2019-12-28' > startdate
                 AND '2019-12-28' < enddate;
© www.soinside.com 2019 - 2024. All rights reserved.