【问题标题】:Find rows where date range intersect the specified date range查找日期范围与指定日期范围相交的行
【发布时间】:2012-12-06 11:09:05
【问题描述】:

我有一个表 leave_applications ,其中包含从日期到现在的两列。我需要从表中获取休假日期在给定月份的那些行,这意味着从日期到日期之间的至少一个日期在给定月份中的行。

因此,我需要一个查询来获取具有两组日期(即 from_date 和 to_date)交集的行以及该月的所有日期。

【问题讨论】:

  • 那么到目前为止你尝试过什么?
  • 我试图构建一个查询,例如 Select * from leave_application where (select date() wher month()= 12 and year()=2012) between from_date and to_date;但这似乎不起作用

标签: php mysql sql date


【解决方案1】:

如果 A C,则两个范围 A-B 和 C-D 重叠。在伪 SQL 中,

select * from leave_applications where 
from_date < (last day of month) AND to_date > (first day of month)

如果 from_date 或 to_date 与该月的第一天和最后一天重合,则使用 = 如果您认为它是重叠的。

【讨论】:

    【解决方案2】:

    我不久前wrote about these queries。这是解决方案:

    -- 2.2) select date ranges that overlap [d1, d2] (d2 and end_date are inclusive)
    SELECT * FROM <table> WHERE @d2 >= start_date AND end_date >= @d1
    

    所以如果你想查看 2012 年 12 月的叶子,你应该写:

    SELECT * FROM leave_applications
    WHERE '2012-12-31' >= from_date AND to_date >= '2012-12-01'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 2018-07-01
      • 2015-03-15
      • 2014-01-07
      • 1970-01-01
      • 2015-10-05
      相关资源
      最近更新 更多