1

我有一个日历,显示给定月份和年份的事件。DATETIME每个事件在字段中都有开始时间和结束时间。

$org = $_SESSION['org_id'];
$month = 5;
$year = 2013;

以下仅检索在指定月份/年份内开始或结束的事件:

SELECT * FROM events WHERE org='$org' AND 
    ((MONTH(time_start)='$month' AND YEAR(time_start)='$year') OR
    (MONTH(time_end)='$month' AND YEAR(time_end)='$year'))

它不会返回在指定月/年之外开始和结束的事件。

前任。time_start='2013-04-07 12:00:00' time_end='2013-06-07 12:00:00'- 在我 2013 年 5 月的查询中找不到该事件。

如何选择开始、结束或跨越给定月/年的事件?

4

4 回答 4

3
SELECT * FROM events 
WHERE org='$org' 
    AND time_start < '$year-$month-01 00:00:00' + INTERVAL 1 MONTH 
    AND time_end > '$year-$month-01 00:00:00'
;

如果你对 mysql 很好,你甚至可以将字符串转换为日期,其他数据库也可以这样,但是 mysql 对字符串很满意。

于 2013-05-07T20:20:09.607 回答
0

使用BETWEEN

$event_date = date('Ymd',mktime(0,0,0,$month,1,$year));

SELECT * FROM events WHERE org='$org' AND date($event_date) BETWEEN time_start AND time_end;

此查询搜索介于该日期之间的所有事件。

试试这个SQLFiddle看看我的观点。

希望这可以帮助。

于 2013-05-07T20:21:14.090 回答
0

Try adding this to your AND -

((MONTH(time_start)<'$month' AND YEAR(time_start)<='$year') AND
      (MONTH(time_end)>'$month' AND YEAR(time_end)>='$year'))

So your query now becomes (a little clunky, but it should get you in the right direction) -

SELECT * FROM events WHERE org='$org' AND 
    (((MONTH(time_start)='$month' AND YEAR(time_start)='$year') OR
      (MONTH(time_end)='$month' AND YEAR(time_end)='$year')) 
     OR
     ((MONTH(time_start)<'$month' AND YEAR(time_start)<='$year') AND
      (MONTH(time_end)>'$month' AND YEAR(time_end)>='$year')))
于 2013-05-07T20:35:25.590 回答
0
$start = date('Y-m-d', mktime((0,0,0,$month,1,$year)));
$end = date('Y-m-d', mktime((23,59,59,$month+1,0,$year)))

And you need to check for four conditions:

  • Event start date between $start and $end
  • Evend end date between $start and $end
  • $start between event start date and event end date
  • $end between event start date and event end date

SELECT *
FROM events
WHERE org='$org'
AND ( (start_time BETWEEN '$start' AND '$end')
    OR (end_time BETWEEN '$start' AND '$end')
    OR ('$start' BETWEEN start_time AND end_time)
    OR ('$end' BETWEEN start_time AND end_time)
)
于 2013-05-07T20:52:01.927 回答