2013-06-27 73 views
1

我要檢查一些時間與特定時間的MySQL重疊計劃 像:發現多時間重疊

time_plan1 = 2011-06-30, startTime = 09:00:00, finishTime = 10:00:00 
time_plan2 = 2011-06-30, startTime = 12:30:00, finishTime = 13:30:00 
time_plan3 = 2011-06-30, startTime = 14:00:00, finishTime = 15:30:00 
time_plan4 = 2011-06-30, startTime = 17:00:00, finishTime = 18:00:00 

和時間

time1 = 2011-06-30, startTime = 08:30:00, finishTime = 10:00:00 
time2 = 2011-06-30, startTime = 12:30:00, finishTime = 13:30:00 
time3 = 2011-06-30, startTime = 14:00:00, finishTime = 15:00:00 
time4 = 2011-06-30, startTime = 16:30:00, finishTime = 19:00:00 

,所以我必須找時間計劃之間的重疊和時間爲每對夫婦的時間計劃和時間,但我不能指定哪個時間屬於哪個時間計劃

更新

的結果,我需要有時間的總和那些屬於時間在這種情況下,計劃 : 時間1:1 H 時間2:1 H 時間3:1 H 時間4:1 H 總和2011-06-30:4h中

+2

救你嘗試過什麼? –

+1

是的!但沒有幸運。 「select * *** WHERE time1.startTime> time_plan1.startTime和time1.finishTime

+1

您可以顯示數據如何被拉出/存儲嗎? –

回答

1

謝謝王牌 你的迴應幫助我找到答案.. 在歷史

foreach($plan as $wpk=>$pla){ 
     foreach($work as $wtk=>$wor){ 
     if($wor['start']<$pla['end'] and $wor['end']>$pla['start']){ 
      $overlap_start = max($wor['start'],$pla['start']); 
      $overlap_finis = min($wor['end'], $pla['end']); 
      $sum += $overlap_finis - $overlap_start; 
      if($overlap_start>$wor['start']) 
      $work[] = array('start'=>$wor['start'],'end'=>$overlap_start); 
      if($wor['end']>$overlap_finis) 
      $work[] = array('start'=>$overlap_finis,'end'=>$wor['end']); 
      unset($work["$wtk"]); 
        } 
        } 
2
WHERE time1.startTime > time_plan1.startTime and time1.finishTime < time_plan1.finishTime 

這幾乎是正確的,但是您只能得到時間比時間計劃晚,並且時間比時間計劃更早完成的場景。

要獲得重疊,

WHERE time1.startTime < time_plan1.startTime or time1.finishTime > time_plan1.finishTime 

這樣做是趕上這3種重疊的情況下

  • 時間早於開始時間開始,但不遲於finishTime完成
  • 時間早啓動比開始時間並且也比完成時間更早結束時間
  • 時間比startTime晚,但比finishTime晚完成時間

棘手的部分是獲得重疊的總和,我認爲你需要PHP因爲這將是複雜的由sql處理。

假設您已經用時間和時間計劃的startTime和finishTime字段收到了您的記錄。

$sum = 0; // seconds 
foreach ($records as $record) { 
    $overlap_start = max($record->time_startTime, $record->timeplan_startTime); 
    $overlap_finish = min($record->time_finishTime, $record->timeplan_finishTime); 
    $sum += strtotime($overlap_finish) - strtotime($overlap_start); 
} 
+1

謝謝,但是當我更多地想到您的解決方案時,我變得更加困惑!當在查詢'WHERE time1.startTime time_plan1.finishTime'中使用'或'時,它會返回每一天的所有記錄,因爲所有記錄的開始時間或結束時間都較短!但起初我們必須找到重疊的時間,然後去php來計算總和! –

+0

啊,對不起。我想你也必須包括日期。 – ace