簡體   English   中英

選擇在MySQL范圍之間的所有時間戳

[英]Select all timestamps that is between range in MySQL

我正在研究類似我的項目的日歷。

我有一個如下表:

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標記,因此這是一種獲取給定日期所需的“開始”和“結束”時間戳的簡單方法,在我的示例中,我將使用“今天”作為目標日期。

$timezone = new DateTimeZone('UTC');
$date = new DateTime('today', $timezone);

$start = $date->getTimestamp();
$end   = $date->add(new DateInterval('P1D'))->getTimestamp();

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM