Checking if new interval overlaps - MySQL (or PHP)

前端 未结 2 800
隐瞒了意图╮
隐瞒了意图╮ 2021-01-19 11:20

I\'ve been thinking on how I can simplify the problem presented here. Complex MySQL Query - Checking for overlapping DATE intervals

At it\'s heart, minus all the fa

2条回答
  •  孤独总比滥情好
    2021-01-19 12:06

    Using folowing abbreviations:

    • [old] := existing range
    • [new] := inserting range
    • OS := (old) existing_range.start
    • OE := (old) existing_range.end
    • NS := (new) inserting_range.start
    • NE := (new) inserting_range.end

    the condition for overlaping of two ranges (old and new) is: (OS < NE) AND (OE > NS)

    While the solution might be not trivial, its not that difficult to get there:

    There is no overlaping if the new range is completly before or after the existing range: [new] <= [old] OR [old] <= [new] and that means that:

    (NE <= OS) OR (OE <= NS)
    

    Negotiating this statement we get the condition for overlaping:

    !( (NE <= OS) OR (OE <= NS) )
    

    Now using De Morgan's law we can write it as

    !(NE <= OS) AND !(OE <= NS)
    

    And this is equivalent to

    (NE > OS) AND (OE > NS)
    

    wich can be rewriten as

    (OS < NE) AND (OE > NS)
    

    Now we can find all overlaping ranges using

    SELECT o.*
    FROM Schedules o
    WHERE o.start < :new_end
      AND o.end   > :new_start
    

提交回复
热议问题