2017-09-09 71 views
0

enter image description hereSQL查詢overlaping時間

我有類預訂名book表。 我也有一張桌子,上面有房間數據,叫做room

我試圖提出一個條件,如果房間已經預訂了特定的時間段,例如上午08:00到上午09:00 - 您無法預訂課程。但如果沒有,那麼你可以。

我的SQL是:

SELECT * FROM book WHERE room_id = '$room_id' and start_date = '$date' and start_time = '$starttime' BETWEEN (SELECT MIN(start_time) AS mintime 
FROM book WHERE room_id = '$room_id' and start_date = '$date') and (SELECT MAX(end_time) AS maxtime 
FROM book WHERE room_id = '$room_id' and start_date = '$date') 

如果SQL返回一行,則該用戶不能預訂了房間。

有時候這個sql有效,但有時會失敗。 是我正在做什麼?

SELECT * 
FROM book 
WHERE room_id = '$room_id' AND 
     start_date = '$date' AND 
     start_time = '$starttime' 
BETWEEN (SELECT MIN(start_time) AS mintime 
     FROM book 
     WHERE room_id = '$room_id' AND 
       start_date = '$date') AND 
     (SELECT MAX(end_time) AS maxtime 
     FROM book 
     WHERE room_id = '$room_id' AND 
       start_date = '$date') 

現在,你可以清楚地看到你只使用一個表,即book但兩個子查詢:

回答

0

,如果你寫出來的可讀格式查詢它經常幫助。這似乎有點多,你沒有以正確的方式使用BETWEEN。爲什麼不這樣的查詢:

SELECT * 
FROM book 
WHERE room_id = '$room_id' AND 
     start_date = '$date' AND 
     '$starttime' BETWEEN start_time AND end_time 

我應該,當然,warn about SQL-injection

+0

謝謝!我改變了它,它工作。如果遇到問題,稍後會與您聯繫。歡呼! –