2012-09-10 73 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的评价,或者我喜欢说,拖延是棘手。