mysql时间段交集查询

可订房间的查询逻辑(时间段没有相交的时间段),这个sql可以直接扔到navicat运行校验下

相交分为以下四种情况情况

在这里插入图片描述


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);
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值