我得到了一个包含一些 DATETIME
范围的表,类似于:
id | start | end
----------------------------------------------
1 | 2011-12-18 16:00:00 | 2011-12-18 17:00:00
2 | 2011-12-19 08:00:00 | 2011-12-19 10:00:00
3 | 2011-12-19 11:00:00 | 2011-12-19 13:00:00
4 | 2011-12-19 12:00:00 | 2011-12-19 14:00:00
5 | 2011-12-19 13:00:00 | 2011-12-19 15:00:00
6 | 2011-12-19 13:00:00 | 2011-12-19 14:00:00
7 | 2011-12-20 13:00:00 | 2011-12-20 14:00:00
因此,对于2011年12月19日,范围如下:
8 9 10 11 12 13 14 15
<-------->
<-------->
<-------->
<-------->
<---->
当插入新的记录时,目标是找到已经存在的最大重叠范围数量:例如:当插入新的范围2011-12-19 12:00:00 - 2011-12-19 15:00:00
时,我希望收到3
,因为最大重叠范围的数量是3,从13:00到14:00。
现在我已经实现了这个功能。
select
count(*) as cnt
from
mytable as p
where
( # check if new renge overlap existings ones
(@start >= start and @start < end)
or
(@end > start and @end <= end)
)
or
( # check if existing range is included by new one
start between @start and @end
and
end between @start and @end
)
但是这会返回
4
,因为它检测除第一个外的所有范围,但是这是错误的。我已经找到了以下内容: 但是所有这些问题都略有不同。
我使用的是MySQL 5.7,但如果必要,升级到8是可能的。