How to check if two date ranges overlap in mysql?

后端 未结 4 1514
死守一世寂寞
死守一世寂寞 2021-01-01 03:31

In mysql, how can I check if two date ranges overlap?

I have this:

Note: We have that p.date_started <= p.date_finished but dateA

4条回答
  •  温柔的废话
    2021-01-01 04:21

    If we are guaranteed that date_started, datefinished, $DateA and $DateB are not NULL, and we're guaranteed that date_started is not greater than date_finished...

    `s` represents `date_started`
    `f` represents `date_finished`
    `a` represents the smaller of `$DateA` and `$DateB`
    `b` represents the larger of `$DateA` and `$DateB`
    

    Visually:

          s-----f       overlap
     -----+-----+-----  -------  
      a-b |     |        NO
      a---b     |        YES
      a-----b   |        YES
      a---------b        YES
      a-----------b      YES
          a---b |        YES
          a-----b        YES
          a-------b      YES
          | a-b |        YES
          | a---b        YES     
          | a-----b      YES     
          |     a-b      YES
          |     | a-b    NO
    

    We can easily detect when there's no "overlap" of the ranges:

    ( a > f OR b < s )
    

    And we can easily negate that to return "true" when there is an "overlap":

    NOT ( a > f OR b < s )
    

    Converting that to SQL:

    NOT ( GREATEST('{$dateA}','{$dateB}') < p.date_started
          OR LEAST('{$dateA}','{$dateB}') > p.date_finished
        )
    

提交回复
热议问题