sql >> Base de Datos >  >> RDS >> Mysql

¿Cómo verificar si dos rangos de fechas se superponen en mysql?

Si tenemos la garantía de que date_started , datefinished , $DateA y $DateB no son NULL, y estamos garantizados que date_started no es mayor que 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`

Visualmente:

      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

Podemos detectar fácilmente cuando no hay "superposición" de los rangos:

( a > f OR b < s )

Y podemos negarlo fácilmente para devolver "verdadero" cuando hay una "superposición":

NOT ( a > f OR b < s )

Convirtiendo eso a SQL:

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