2012-09-05 36 views
0

下面的查詢MySQL和查詢中使用兩次不起作用

SELECT * FROM workshops 
WHERE workshop_zipcode LIKE '75___' 
    OR workshop_zipcode LIKE '77___' 
    AND workshop_category = 14 
    AND active = 1 
    AND workshop_date >= NOW() 
ORDER BY workshop_date ASC 

不會產生任何錯誤,和實際工作,但有一個小問題:這一部分

AND workshop_date >= NOW() 

不要過濾任何東西,以相同的方式替換比較符號,並檢索相同的列表。

兩個第一個AND效果不錯,但第三個不行。

回答

5

你需要圓括號您OR條件像這樣:

SELECT * FROM workshops 
WHERE (workshop_zipcode LIKE '75___' 
OR workshop_zipcode LIKE '77___') 
AND workshop_category = 14 
AND active = 1 
AND workshop_date >= NOW() 
ORDER BY workshop_date ASC 

如果沒有括號,你在本質上調用此:

SELECT * FROM workshops 
WHERE workshop_zipcode LIKE '75___' 
OR (workshop_zipcode LIKE '77___' 
AND workshop_category = 14 
AND active = 1 
AND workshop_date >= NOW()) 
ORDER BY workshop_date ASC 

這是因爲AND是在之前計算的。看到這個參考

http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html

+0

它的工作原理,謝謝! – SupFrig

0

嘗試這樣的:

SELECT * FROM workshops 
WHERE (workshop_zipcode LIKE '75___' 
OR workshop_zipcode LIKE '77___') 
AND workshop_category = 14 
AND active = 1 
AND workshop_date >= NOW() 
ORDER BY workshop_date ASC 
+0

aaaaand也謝謝你 – SupFrig

1

這可能是與運算符優先級的問題。

SQL將首先評估所有AND語句,然後評估OR語句;如果你把他們周圍的括號,你可能會得到期望的結果:

SELECT * FROM workshops 
WHERE (workshop_zipcode LIKE '75___' 
OR workshop_zipcode LIKE '77___') 
AND workshop_category = 14 
AND active = 1 
AND workshop_date >= NOW() 
ORDER BY workshop_date ASC 

這將檢查車間郵編,然後你的標準的其餘部分。

+0

感謝回覆,如上所述,它運作良好。謝謝 – SupFrig