这是在插入查询中检查日期重叠的简单方法
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
编号 |开始日期 |结束日期
-: | :--------- | :---------
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
编号 |开始日期 |结束日期
-: | :--------- | :---------
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
编号 |开始日期 |结束日期
-: | :--------- | :---------
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