2013-02-25 15 views
0

我有一個由event_id,event_name,event_start_date和event_end_date組成的'events'表。如何插入新的事件不會落在其他事件之間?

我遇到的問題是,當插入一個新事件時,我需要檢查從新指定的新事件到新事件的日期之間是否沒有先前的事件。

沒有兩個事件可能在event_to_date和event_form_date之間。

我正在使用PHP和MySql。

+0

你最好在你的數據庫中強制執行。也許使用觸發器功能,如果出現不需要的情況,則會引發錯誤。 – Eggplant 2013-02-25 11:03:06

回答

0

您應該使用SQL檢查將發生衝突事件的數量:

<?php 

// do your mysql connection 

// count collided events 
$sql = 'SELECT COUNT(*) as count FROM events WHERE event_start_date <= "'. 
    mysql_real_escape_string($new_event_end_date).'" AND event_end_date >= "'. 
    mysql_real_escape_string($new_event_start_date).'"'; 

$result = mysql_query($sql); 

if (($row = mysql_fetch_assoc($result)) != FALSE) { 
    if ($row['count'] == 0) { 
    // insert the event normally 
    } else { 
    trigger_error('Error: There are '.$row['count'].' event(s) within this period.'); 
    } 
} else { 
    trigger_error('Unknown server error: '.mysql_error()); 
} 
?> 
0

基本上你正在尋找的重疊,這是一種僞十歲上下,其中candidate_X是輸入數據和existing_Y是什麼在你的分貝。

該解決方案將取決於什麼樣的領域,你保存你的日期。

毫無疑問,這是可以改善的,也許使用等之間

SELECT ID from events WHERE 
(candidate_from < existing_to 
AND 
candidate_to > existing_to) 
OR 
(candidate_to > existing_from 
AND 
candidate_to < existing_to) 

如果產生任何結果的話,就意味着你的數據庫中有些東西會重疊,因此你可以返回說事件的ID。

這不是測試順便說一句。

+0

由於'candidate_to> existing_from'包含'candidate_to> existing_to',所以不需要後者。類似地,'candidate_from existing_from',後者不需要。因此只有'candidate_to> existing_from和candidate_from 2013-02-25 11:27:28

+0

也許就在那裏,我只是在大聲思考,並認爲它會幫助OP降低邏輯 - 在發佈時,我發現了你的回覆,並認爲,「......好好留下吧......」認爲這可能會有幫助OP作爲一種墊腳石。 – Cups 2013-02-25 14:11:33

相關問題