2012-11-22 48 views
2

我有以下帶有列的數據庫表。查找數據庫表中是否有時隙可用

+----+---------------------+---------------------+------------------+ 
| id | start_datetime  | end_datetime  | arena_surface_id | 
+----+---------------------+---------------------+------------------+ 
| 1 | 2012-11-22 02:30:00 | 2012-11-22 05:00:00 |    2 | 
| 2 | 2012-11-22 00:00:00 | 2012-11-22 02:30:00 |    2 | 
| 3 | 2012-11-22 05:00:00 | 2012-11-22 08:00:00 |    2 | 
| 4 | 2012-11-22 08:00:00 | 2012-11-22 11:00:00 |    2 | 
| 5 | 2012-11-22 11:00:00 | 2012-11-22 17:00:00 |    2 | 
+----+---------------------+---------------------+------------------+ 

帶日期的用戶輸入,開始時間和結束時間,我想看看是否有給定的時間內預訂了特定arena_surface_id任何插槽。

例如,如果用戶輸入是。

start_datetime : 2012-11-22 6:00 
end_datetime : 2012-11-22 9:00 
arena_surface_id : 2 

我想知道是否有相匹配6:00和9:00在指定日期時間之間的時隙(在上面的例子中它應匹配)的任何行。

什麼是適當的MySQL查詢呢?

這實際上是這個how would I detect a non-overlap of two time periods?

UPDATE

@March這是一個後續的問題是什麼,當我用你的查詢返回。

SELECT 
    id, 
    start_datetime, 
    end_datetime, 
    arena_surface_id 
FROM 
    gce_arena_surface_booking 
WHERE 
    (start_datetime BETWEEN '2012-11-22 04:00:00' AND '2012-11-22 09:00:00') 
OR 
    (end_datetime BETWEEN '2012-11-22 4:00:00' AND '2012-11-22 9:00:00') 


+----+---------------------+---------------------+------------------+ 
| id | start_datetime  | end_datetime  | arena_surface_id | 
+----+---------------------+---------------------+------------------+ 
| 1 | 2012-11-22 02:30:00 | 2012-11-22 05:00:00 |    2 | 
| 3 | 2012-11-22 05:00:00 | 2012-11-22 08:00:00 |    2 | 
| 4 | 2012-11-22 08:00:00 | 2012-11-22 11:00:00 |    2 | 
+----+---------------------+---------------------+------------------+ 

中間記錄不符合條件,仍然提取它。

+0

http://mattgemmell.com/2008/12/08/what-have-you-tried/ – Ankur

回答

7

如何

SELECT * 
FROM yourTable 
WHERE (startTime BETWEEN 'yourStartImput' AND 'yourEndImput') OR (endTime BETWEEN 'yourStartImput' AND 'yourEndImput') 

所以你檢查是否有啓動或您的輸入端之間的匹配。

的評論,您的最終查詢應該是這樣的:

SELECT * 
FROM yourTable 
WHERE ((startTime BETWEEN 'yourStartImput' AND 'yourEndImput') 
    OR (endTime BETWEEN 'yourStartImput' AND 'yourEndImput')) 
    AND arena_surface_id = 1 
+0

我試圖用這種方式它給了我語法錯誤。 'SELECT * FROM gce_arena_surface_booking WHERE(start_datetime BETWEEN 2012-11-22 4:00 AND 2012-11-22 9:00)或(end_datetime BETWEEN 2012-11-22 4:00 AND 2012-11-22 9:00); ' –

+0

你需要在你的日期單引號 – Marc

+0

是的,它現在提取,但在中間有一個錯誤的記錄被提取。虐待更新我的問題,它返回什麼,你可以看看這個問題。 –

相關問題