这是我很多年前找到答案的查询模式:
SELECt *FROM mytable aJOIN mytable b on a.starttime <= b.endtime and a.endtime >= b.starttime and a.name != b.name; -- ideally, this would compare a "key" column, eg id
要找到“任何重叠”,您可以将时间范围的 相对 两端彼此进行比较。我必须掏出笔和纸,画出相邻的范围,以便意识到边缘情况归结为这种比较。
如果要防止任何行重叠,请将此查询的变体放入触发器中:
create trigger mytable_no_overlapbefore insert on mytablefor each rowbegin if exists (select * from mytable where starttime <= new.endtime and endtime >= new.starttime) then signal sqlstate '45000' SET MESSAGE_TEXT = 'Overlaps with existing data'; end if;end;



