【问题标题】:php mysql double date rangephp mysql 双日期范围
【发布时间】:2011-12-19 10:00:03
【问题描述】:

我正在处理一个事件 callendar,但无法找到一个在给定范围内选择我的事件的 mysql 查询。我的活动有开始/结束日期,我的范围(月)也是如此。

我已尽力描述我正在寻找的内容:(我想选择事件 1、2、3、4 但不是 5 或 6)

         |========= April ===========|            => Range
     +--(1)--+                   +--(2)--+        => Partialy Overlapping Events
                   +--(3)--+                      => Events included in range
     +----------------(4)----------------+        => Ovelapping events
+-(5)-+                                 +-(6)-+   => Events outside of range

我发现了类似的问题:2 Column Mysql Date Range Search in PHP 但我不认为这是重复的,好像我在我的问题中正确理解范围有开始和结束日期,而在另一个问题中范围是单个日期。

【问题讨论】:

  • 您的范围是如何给出的,您的事件表的表架构是什么?

标签: php mysql date range


【解决方案1】:

解决方案仍然与您链接的问题非常相似;试试这个查询:

SELECT * FROM events e
    WHERE `start` <= [RANGE.end]
    AND `end`  >= [RANGE.start]

您当然必须将 [RANGE.start] 和 [RANGE.end] 替换为范围的第一个和最后一个日期。如果例如RANGE.start = '2011-04-01' 和 RANGE.end = '2011-04-30',上面的查询将给出 11 年 4 月发生的所有结果。

根据您是否要选择仅“触摸”范围的事件(意味着它们具有共同的边界日期,但实际上并不重叠),您可以将 &lt;=/&gt;= 替换为 &lt; /&gt;.

【讨论】:

  • 我现在明白了,很有道理
  • 我试图对此进行非常大的查询,您为我节省了很多时间,谢谢。
【解决方案2】:

试一试。我编了一张表dateRangeExample来说明答案:

drop table if exists dateRangeExample;

create table dateRangeExample
(id int unsigned primary key,
startDate date not null,
endDate date not null
);


insert into dateRangeExample (id,startDate,endDate) values (1,'2011-03-15','2011-04-05');
insert into dateRangeExample (id,startDate,endDate) values (2,'2011-04-25','2011-05-05');
insert into dateRangeExample (id,startDate,endDate) values (3,'2011-04-10','2011-04-15');
insert into dateRangeExample (id,startDate,endDate) values (4,'2011-03-15','2011-05-05');
insert into dateRangeExample (id,startDate,endDate) values (5,'2011-03-01','2011-03-20');
insert into dateRangeExample (id,startDate,endDate) values (6,'2011-05-03','2011-05-25');

select dre.*
from dateRangeExample dre
where startDate between '2011-04-01' and '2011-04-30'
or endDate between '2011-04-01' and '2011-04-30'
or (startDate < '2011-04-01' and endDate > '2011-04-30');

【讨论】:

    猜你喜欢
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    相关资源
    最近更新 更多