簡體   English   中英

查詢以檢查給定的日期范圍是否不適合多個日期范圍

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

我有一個包含 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 ,它會重疊一個范圍,所以我無法將它添加到表中。

我知道如何逐行檢查范圍,但不知道如何在整個表格中進行檢查。

好吧,如果它們重疊,則給定范圍的任何一個邊界都在表中的范圍內。 因此,您可以使用以下內容:

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的子查詢中聲明。 如果表中的任何記錄與該范圍重疊,則跳過插入,否則會發生。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM