Mysql或/和优先级?

时间:2012-09-10 05:01:57

标签: mysql operator-precedence

我想知道如何和/并且有效?

例如,如果我想获取display = 1

的所有行

我可以WHERE tablename.display = 1

如果我想要所有行显示= 1或2

我可以WHERE tablename.display = 1 or tablename.display = 2

但是如果我想获取display = 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%")

4 个答案:

答案 0 :(得分:29)

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%")
    )

答案 1 :(得分:4)

运行此查询:

select 1 or 1 and 0

如果它出现为1,则表示优先级为:

select 1 or (1 and 0)

如果它出现0,则优先级为:

select (1 or 1) and 0

剧透:它出来1

也就是说,AND s在OR之前进行评估,或者正如我想说的那样,AND更加坚固。

答案 2 :(得分:3)

您需要为多个OR条件使用括号。对于display = 1 OR display = 2,您可以使用display IN(1,2)。试试这个:

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

有关详细信息,请查看MySQL: Operator Precedence

答案 3 :(得分: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)