2011-01-19 50 views
1

我試圖在MySQL數據庫上運行查詢,但我發現它似乎忽略了'狀態'項。與多個AND語句的MySQL查詢似乎忽略一個

SELECT * FROM `posts` 
WHERE 
     `tags` LIKE '%gda%' 
    OR `tags` LIKE '%contests%' 
    OR `tags` LIKE '%merch%' 
    AND `newsID` != '2134' 
    AND `status` > '1' 
ORDER BY `postDate` DESC LIMIT 5 

在這個例子中,即使'status'被設置爲0,它仍然在拉動項目。我在做什麼錯了?

回答

7

問題在於優先級爲OR/AND的條件。 AND的優先級高於OR,這就是爲什麼它首先評估AND(tags-merch,newsID-2134和status-1)所連接的所有條件,然後評估兩個標籤-gda和標籤競賽)。

嘗試添加括號:

SELECT * 
    FROM `posts` 
WHERE (`tags` LIKE '%gda%' 
    OR `tags` LIKE '%contests%' 
    OR `tags` LIKE '%merch%') 
    AND `newsID` != '2134' 
    AND `status` > '1' 
ORDER BY `postDate` DESC 
LIMIT 5 
+0

工作。這是我第一次開始使用足夠複雜的查詢,這樣的東西成爲一個問題。有道理,但感謝解釋和示例。 – Andelas 2011-01-19 09:02:15

1

你嘗試過這樣的:

SELECT * FROM `posts` 
WHERE 
    (`tags` LIKE '%gda%' 
    OR `tags` LIKE '%contests%' 
    OR `tags` LIKE '%merch%') 
    AND `newsID` != '2134' 
    AND `status` > '1' 
ORDER BY `postDate` DESC LIMIT 5 
1

也許你應該使用一些支架,我不知道你想要什麼,但組合試試這個:

SELECT * FROM `posts` 
    WHERE 
     (`tags` LIKE '%gda%' 
     OR `tags` LIKE '%contests%' 
     OR `tags` LIKE '%merch%' 
    ) 
     AND `newsID` != '2134' 
     AND `status` > '1' 
    ORDER BY `postDate` DESC LIMIT 5 
1

通常混合OR和AND不是一個聰明的做法,因爲你會得到不同的結果基於執行順序和運營商優先級(例如,true or true and false)可以被評估爲(true or true) and false - 產生錯誤或者產生錯誤或者產生錯誤true or (true and false)

使用括號來分隔的OR和AND運算,並執行順序將是明確的,就像這樣:

SELECT * FROM `posts` 
WHERE (`tags` LIKE '%gda%' OR `tags` LIKE '%contests%' OR `tags` LIKE '%merch%') 
    AND `newsID` != '2134' 
    AND `status` > '1' 
ORDER BY `postDate` DESC LIMIT 5 
1

嘗試使用括號來強調你的邏輯的句子。如:

SELECT * 
    FROM `posts` 
WHERE (`tags` LIKE '%gda%' OR `tags` LIKE '%contests%' OR `tags` LIKE '%merch%') 
    AND `newsID` != '2134' 
    AND `status` > '1' 
ORDER BY `postDate` DESC LIMIT 5 

否則,您的邏輯會丟失。另外使用括號可以更容易地讀取您的SQL語句

相關問題