2013-10-15 57 views
1

之間的空白時期我有一個MySQL表是這樣的:的MySQL如何檢查兩個日期

| ID | date_start | date_end | 
| 1 | 2013-10-17 | 2013-10-18 | 
| 2 | 2013-10-28 | 2013-10-31 | 

我需要檢查兩個日期之間的空週期。

要從日期範圍檢索記錄我做的:

SELECT * FROM `periods` WHERE ((date_start <= '2013-10-18' AND date_end >= '2013-10-18' AND date_end <= '2013-10-31') OR (date_start >= '2013-10-18' AND date_start <= '2013-10-31' AND date_end >= '2013-10-31') OR (date_start >= '2013-10-18' AND date_end <= '2013-10-31') OR (date_start <= '2013-10-18' AND date_end >= '2013-10-31')) 

在PHP我可以檢查出來while循環,但有可以檢查這個MySQL查詢?的Mysql

$first = true; 
$emptyPeriod = false; 
while ($period = mysql_fetch_assoc($result)) { 
    if($first) { 
     $first = false; 
     $prevEndPeriod = $period['date_end']; 
     continue; 
    } 

    $nextDay = date('Y-m-d', strtotime($prevEndPeriod . ' + 1 day')); 

    if($nextDay != $period['date_start']) { 
     $emptyPeriod = true; 
     break; 
    } else { 
     $prevEndPeriod = $period['date_end']; 
    } 

} 

echo ($emptyPeriod) ? 'Empty period' : 'OK'; 
+0

使用DATEDIFF http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff – Ashalynd

回答

0

使用DATEDIFF功能:

SELECT DATEDIFF('2013-10-17','2013-10-18'); 

欲瞭解更多信息檢查此鏈接:
http://answers.oreilly.com/topic/163-how-to-calculate-the-interval-between-two-dates-or-times-in-mysql/

OR

使用PHP:

floor((strtotime($endDate) - strtotime($startDate))/86400); 
+0

這並不能解決問題或我不明白。我需要檢查兩個日期之間的空白時間段,例如:日期範圍2013-10-17至2013-10-31空閒時間段爲2013-10-19至2013-10-27。 – wandam

+0

檢查我更新的代碼。 –

+0

在PHP中,它工作正常,但我需要一個SQL查詢 – wandam

0

以下查詢將爲您提供重疊期的開始日期。如果有多於一個,則中間有一個空的時段。

select distinct s.date_start 
from periods s 
left join periods e 
    on date_diff(s.date_start, e.date_end) <= 0 
     and date_diff(s.date_start, e.date_end) >= -1 
where e.id is null 

你的PHP代碼將是:

echo (mysql_num_rows($result)>1) ? 'Empty period' : 'OK'; 

如果您需要空時段的開始和結束日期,你可以得到類似的方式重疊時期的結束日期,並走了更進一步。

相關問題