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

时间:2019-12-14 17:56:51

标签: mysql sql database date date-range

我有一个包含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-23 2019-12-28 ,则它与其他范围不重叠,因此我可以添加它在表中。

但是,如果范围从 2019-12-23 2019-12-30 ,则该范围会与该范围重叠,因此我无法将其添加到表格中。 / p>

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分: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  | 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