2012-09-10 183 views
10

我想知道如何或/和作品?Mysql或/和優先級?

例如,如果我想在那裏顯示= 1

我可以做WHERE tablename.display = 1

,如果我想所有行顯示= 1或2

我可以做的所有行WHERE tablename.display = 1 or tablename.display = 2

但是,如果我想獲得的所有行什麼地方顯示= 1或2,其中任何內容,標記或標題中包含hello world

邏輯將如何發揮呢?

Select * from tablename 
where display = 1 or display = 2 and content like "%hello world%" or tags like "%hello world%" or title = "%hello world%" 

會是我的猜測。但是我可以用幾種方式閱讀。

它讀出爲:

(display = 1 or display = 2) and (content like "%hello world%" or tags like "%hello world%" or title = "%hello world%") 

((display = 1 or display = 2) and (content like "%hello world%")) or (tags like "%hello world%" or title = "%hello world%") 

+2

http://dev.mysql.com/doc/refman/5.5/en/operator-precedence.html – zerkms

+0

這些東西是在您早期的C/C++課程中教授的。 –

+3

然後,我想我應該註冊一個完整的C/C++課程,以瞭解運算符的優先級:/ – Hailwood

回答

22

SELECT * FROM tableName 
WHERE display IN (1,2) 
AND (content LIKE "%hello world%" 
OR tags LIKE "%hello world%" 
OR title LIKE "%hello world%") 

欲瞭解更多信息看MySQL文檔有哪個運營商優先考慮信息的good page:試試這個。

在這個頁面,

12.3.1。運算符優先級

運算符優先級顯示在以下列表中,從最高優先級到最低優先級。 一起顯示在一行上的運算符具有相同的優先級。

INTERVAL 
BINARY, COLLATE 
! 
- (unary minus), ~ (unary bit inversion) 
^ 
*, /, DIV, %, MOD 
-, + 
<<, >> 
& 
| 
= (comparison), <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN 
BETWEEN, CASE, WHEN, THEN, ELSE 
NOT 
&&, AND 
XOR 
||, OR 
= (assignment), := 

所以你的原始查詢

Select 
    * 
from tablename 
where 
    display = 1 
    or display = 2 
    and content like "%hello world%" 
    or tags like "%hello world%" 
    or title = "%hello world%" 

會懷疑被解釋爲

Select 
    * 
from tablename 
where 
    (display = 1) 
    or (
     (display = 2) 
     and (content like "%hello world%") 
    ) 
    or (tags like "%hello world%") 
    or (title = "%hello world%") 

時,用括號使你的意圖明確。雖然MySQL頁面上的信息很有幫助,但如果查詢曾經被重新訪問過,則可能不會立即顯而易見。

您可能會考慮類似以下內容。請注意,我已將title = "%hello world%"更改爲title like "%hello world%",因爲這符合您所描述的目標。

Select 
    * 
from tablename 
where 
    (
     (display = 1) 
     or (display = 2) 
    ) and (
     (content like "%hello world%") 
     or (tags like "%hello world%") 
     or (title like "%hello world%") 
    ) 
0

在所有的SQL服務器,AND優先OR,所以只記得把周圍的括號您的OR s:

select * from tablename 
where (display = 1 or display = 2) 
and (content like "%hello world%" 
     or tags like "%hello world%" 
     or title = "%hello world%") 


btw (display = 1 or display = 2)相當於display in (1, 2)

+0

請查看我對我的問題的補充。這與沒有括號有關,它如何發揮出來? – Hailwood

3

您需要爲多個OR條件使用括號。而對於display = 1 OR display = 2,您可以使用display IN(1,2)。在MySQL: Operator Precedence

+0

不,這不會按預期工作 – zerkms

+0

@zerkms現在看。 – hims056

1

運行此查詢:

select 1 or 1 and 0 

如果它出來爲1,那麼這意味着優先級是:

select 1 or (1 and 0) 

如果它出來0,則優先級爲:

select (1 or 1) and 0 

擾流板:它出來1

也就是說,前OR小號AND s的評價,或者我喜歡說,拖延是棘手。