检测数据库时间是否冲突

需求:对一天的时间进行分段,比如:
8:00~10:00,
10:00~12:00,
12:00~14:00,
……
现在要插入一个时间段,检查该时间段是否与已经存在的时间段冲突(即有没有交集)
假设数据库存在一条数据:
这里写图片描述
新增一条数据,开始时间:s,结束时间为:e.
首先画图分析,可能会冲突的情况,假设黑线9:00~11:00为数据库中的数据,共有7种可能
这里写图片描述
第一种:

start_time > 's' and start_time < 'e'

第二种:

start_time = 's' and end_time > 'e'

第三种:

end_time > 's' and end_time < 'e'

第四种:

start_time = 's' and end_time = 'e'

第五种:

start_time < 's' and end_time > 'e'

第六种:

start_time > 's' and end_time < 'e'

第七种:

end_time > 's' and end_time < 'e'

所以,总的sql:

select * from table where 1= 1
and ((start_time > 's' and start_time < 'e')
OR(start_time = 's' and end_time > 'e')
OR(end_time > 's' and end_time < 'e')
OR(start_time = 's' and end_time = 'e')
OR(start_time < 's' and end_time > 'e')
or(start_time > 's' and end_time < 'e')
OR(end_time > 's' and end_time < 'e'))

参考:
https://blog.csdn.net/a312024054/article/details/76786739
https://blog.csdn.net/qqxyy99/article/details/80241251
如果有问题,还望各位指正。上面两位写的很简单,我先用他们的方式解决了我的问题,然后自己一分析,竟然会多出这么几种可能,不知道是不是分析出问题了

发布了33 篇原创文章 · 获赞 24 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/Myc_CSDN/article/details/82151699