PHP MySQL获取与输入日期相比重叠的日期

时间:2019-01-25 08:03:51

标签: php mysql sql date overlap

我需要从数据库中获取重叠的日期行,其中输入的开始日期和结束日期与数据库中的任何行都重叠。

查询:

SELECT * 
  FROM dates
 WHERE date_from >= $dateFrom 
   AND date_from >= $dateTill
    OR date_till >= $dateFrom 
   AND date_till <= $dateTill
    OR date_from <= $dateFrom 
   AND date_till >= $dateTill

当前我有一行,开始日期为:2019-03-11,结束日期为2019-03-17

查询会在以下日期立即跳过它:

Beginning: 2019-03-07
End: 2019-03-16

任何想法如何改善查询?

2 个答案:

答案 0 :(得分:0)

尝试一下:

SELECT *
FROM dates
WHERE (date_from BETWEEN $dateFrom AND $dateTill)
   OR (date_till BETWEEN $dateFrom AND $dateTill)
   OR ($dateFrom BETWEEN date_from AND date_end)

进行一些复杂的逻辑运算时,必须使用括号。

还要查看逻辑运算符的工作方式:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

答案 1 :(得分:0)

select * FROM table_name WHERE (date_from BETWEEN $dateFrom AND $dateTill)  OR (date_till BETWEEN $dateFrom AND $dateTill) OR ($dateFrom BETWEEN date_from AND date_end)

我认为这对您有所帮助。