2014-09-28 114 views
0

之間我有這樣的查詢比較與MySQL

SELECT * 
FROM `reservations` 
WHERE '2014-09-04' BETWEEN check_in AND check_out 

在另一種情況下,多個日期,我需要這個CHECK_IN和CHECK_OUT場比較多個日期。此查詢可以解決該問題

SELECT * 
FROM `reservations` 
WHERE '2014-09-04' BETWEEN check_in AND check_out 
     OR '2014-09-09' BETWEEN check_in AND check_out 

但是,如果我有很多日期進行比較,則此查詢效率不高。任何人都有解決方案使這個查詢更短?

回答

2

縮短查詢:

SELECT DISTINCT r.* 
FROM reservations r 
JOIN (
    SELECT '2014-09-04' AS dt UNION 
    SELECT '2014-09-09' AS dt 
) dates ON dates.dt BETWEEN r.check_in AND r.check_out 
+0

感謝您的解決方案 – l1th1um 2014-09-28 23:07:30

1

如果您在check_incheck_out上沒有索引,則使用or的多個條件是最佳方法。如果你對這些列的索引和它們在第一種情況下被使用,那麼請嘗試使用union

SELECT * 
FROM `reservations` 
WHERE '2014-09-04' BETWEEN check_in AND check_out 
UNION 
SELECT * 
FROM `reservations` 
WHERE '2014-09-09' BETWEEN check_in AND check_out ; 

注意union即被刪除重複的開銷。我正在使用它,因爲你可能在結果中有重複,並且大概你不需要它們。一般來說,我建議儘可能使用union all

+0

感謝您的解釋 – l1th1um 2014-09-28 23:06:48

0

如果您需要檢查重疊:

SELECT * 
FROM reservations 
WHERE '2014-09-04' <= check_out AND '2014-09-09' >= check_in