可订房间的查询逻辑(时间段没有相交的时间段),这个sql可以直接扔到navicat运行校验下
相交分为以下四种情况情况
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/db2a40e5ab636ad754704244b397c7dd.png)
drop table if EXISTS `test_date`;
CREATE TABLE `test_date` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`room_id` int(11) DEFAULT NULL COMMENT '房间id',
`start_time` datetime DEFAULT NULL COMMENT '房态开始时间',
`end_time` datetime DEFAULT NULL COMMENT '房态结束时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `test`.`test_date`(`id`, `room_id`, `start_time`, `end_time`)
VALUES (1, 1, '2020-05-20 15:00:00', '2020-05-22 12:00:00');
INSERT INTO `test`.`test_date`(`id`, `room_id`, `start_time`, `end_time`)
VALUES (2, 1, '2020-05-25 15:00:00', '2020-05-27 12:00:00');
-- 查询入住时间
set @s = '2020-05-18 23:59:59';
-- 查询离店时间
set @e = '2020-05-21 00:00:00';
-- 这个sql查询出来的话,是不合适的数据,有重叠
select * from test_date
where
(start_time <= @s and end_time >= @s)
or
(start_time <= @e and end_time >= @e)
or
(start_time >= @s and end_time <= @e)
or
(start_time <= @s and end_time >= @e);
-- 这个sql不加反,求出来的是合适的数据,不重叠的数据
-- 取反,就是重叠的数据,日期不符合规范的数据,有相交的数据
select * from test_date
where
!(start_time >= @e or end_time <= @s);