我正在为我的一个项目开发一个类似日历的功能。
我有一个如下所示的表:
ID | Title |Where |tri| Start | End | tro
______________________________________________________________________
"4"|"Planingfrenzy" |"Street 8"|"0"|"1395835200"|"1395846000"|"1"
"5"|"Other meeting" |"Road 8" |"0"|"1395140400"|"1395158400"|"1"
"6"|"Third meeting" |"Lane 8" |"0"|"1395819000"|"1395824400"|"1"
"8"|"Weekend at cyprus"|"Cyprus" |"0"|"1395928800"|"1396162800"|"1"
我在选择一天内发生的所有事件时有问题。我尝试了以下两个查询,但它们只返回那些在同一天开始和结束的事件。
/*
Start is a unixtimestamp for the beginning of the day
End is a unixtimestamp for the end of the day
*/
//This Returns to many events since all events that ends before the end timestamp is a match etc.
SELECT * FROM events WHERE (start > ? OR end<?)
//This matches all events that start and end at the same day. But a multi day event like "Weekend at cyprus" isn't returned since it is out of range
SELECT * FROM events WHERE (start > ? AND end<?)
是否有一些方式在MySQL或PHP匹配如果开始/结束范围"触摸"在查询的时间戳范围?
假设?
的两个值是当天最早和最晚的值,我认为您需要:
where start < (?end) and end > (?start)
也就是说,当一个元素的开始在另一个元素的结束之前时存在重叠,反之亦然。
在这个答案中,(?end)
打算作为当天的最后一个时间戳,(?start)
打算作为第一个时间戳。
在这种情况下,正确的表达式是使用BETWEEN:
SELECT * FROM events WHERE 1 AND date BETWEEN start AND end
MySQL文档我假设您想捕获在您定义的时间范围内具有开始时间或结束时间的任何事件。
我实际上没有在你的数据集上测试,但这应该让你朝着正确的方向前进:
SELECT * FROM events
WHERE (Start >= :start AND Start < :end)
OR (End >= :start AND End < :end)
因为你已经在你的问题中包含了PHP标签,这里有一个简单的方法来获得"开始"answers"结束"时间戳,你需要一个给定的日期,在我的例子中,我将使用"今天"作为目标日期。
$timezone = new DateTimeZone('UTC');
$date = new DateTime('today', $timezone);
$start = $date->getTimestamp();
$end = $date->add(new DateInterval('P1D'))->getTimestamp();