Checking a table for time overlap?

后端 未结 4 529
走了就别回头了
走了就别回头了 2020-11-28 09:23

I have a MySQL table with the following fields:

  • name
  • starttime
  • endtime

starttime and endtime are MyS

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 09:51

    This is a query pattern for which I found the answer many years ago:

    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
    

    To find "any overlap", you compare the opposite ends of the timeframe with each other. It's something I had to get a pen and paper out for and draw adjacent ranges to realise that the edge cases boiled down to this comparison.


    If you want to prevent any rows from overlapping, put a variant of this query in a trigger:

    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;
    

提交回复
热议问题