2016-11-02 77 views
1

我有一個MySQL的問題,我試圖獲得所有的預訂,其中開始時間大於'16:42'但小於'18:42'。我試過這個,但是當我用'15:42'而不是'16:42'時,我仍然得到了同樣的結果。按時間獲取預訂

SELECT  * 
FROM  `tables` 
INNER JOIN reservation_table 
ON   `tables`.`id` = reservation_table.table_id 
INNER JOIN reservations 
ON   reservations.id = reservation_table.reservation_id 
INNER JOIN customers 
ON   customers.id = reservations.customer_id 
WHERE `date` = '2016-11-02' 
    AND (starttime <= '19:42' 
     AND starttime >= '16:42') 

This is the result of the query

+1

爲什麼不合並的日期和時間爲一個字段:http://stackoverflow.com/questions/5786649/mysql-get-record-count-between-two-date-time – Maximus2012

+2

其數據類型是colu開始時間? – scaisEdge

+0

它的時間數據類型 –

回答

1

可能是你有一些轉換的問題..嘗試使用一個明確的轉換

SELECT  * 
FROM  `tables` 
INNER JOIN reservation_table 
ON   `tables`.`id` = reservation_table.table_id 
INNER JOIN reservations 
ON   reservations.id = reservation_table.reservation_id 
INNER JOIN customers 
ON   customers.id = reservations.customer_id 
WHERE `date` = '2016-11-02' 
    AND (starttime <= str_to_date('19:42', '%H:%i') 
     AND starttime >= str_to_date('16:42' , '%H:%i')) 
+0

它不起作用:( –

+0

什麼意思不起作用..你有錯誤?..錯誤的結果。?。沒有結果? – scaisEdge

+0

我沒有得到任何結果,如果我使用str_to_date()。 –

0

如果starttimeendtime列是TIME格式那麼該查詢應該解決您的問題:

因爲mysql文檔說「如果NO_ ZERO_DATE或NO_ZERO_IN_DATE啓用SQL模式,不允許零日期或部分日期。「您可能需要執行這個查詢第一:

SET sql_mode = ''; 

然後第二個(如果開始時間和結束時間列在時間格式):

SELECT  * 
FROM  `tables` 
INNER JOIN reservation_table 
ON   `tables`.`id` = reservation_table.table_id 
INNER JOIN reservations 
ON   reservations.id = reservation_table.reservation_id 
INNER JOIN customers 
ON   customers.id = reservations.customer_id 
WHERE `date` = '2016-11-02' 
AND (starttime <= str_to_date('19:42', '%H:%i') 
    AND starttime >= str_to_date('16:42' , '%H:%i')) 

,但如果這些列不是該格式做:

SELECT  * 
FROM  `tables` 
INNER JOIN reservation_table 
ON   `tables`.`id` = reservation_table.table_id 
INNER JOIN reservations 
ON   reservations.id = reservation_table.reservation_id 
INNER JOIN customers 
ON   customers.id = reservations.customer_id 
WHERE `date` = '2016-11-02' 
AND (str_to_date(starttime, '%H:%i') <= str_to_date('19:42', '%H:%i') 
    AND str_to_date(starttime, '%H:%i') >= str_to_date('16:42' , '%H:%i'))