Boh*_*ian 33
这是我多年前找到答案的查询模式:
SELECT *
FROM mytable a
JOIN 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
Run Code Online (Sandbox Code Playgroud)
要找到"任何重叠",您可以将时间帧的相反两端相互比较.这是我必须得到笔和纸张并绘制相邻范围以实现边缘情况归结为这种比较的东西.
如果要防止任何行重叠,请将此查询的变体放在触发器中:
create trigger mytable_no_overlap
before insert on mytable
for each row
begin
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;
Run Code Online (Sandbox Code Playgroud)