需求:对一天的时间进行分段,比如:
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
如果有问题,还望各位指正。上面两位写的很简单,我先用他们的方式解决了我的问题,然后自己一分析,竟然会多出这么几种可能,不知道是不是分析出问题了