Hai*_*ood 16 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%"
Run Code Online (Sandbox Code Playgroud)
我的猜测.但后来我可以通过几种方式阅读.
它是否读出:
(display = 1 or display = 2) and (content like "%hello world%" or tags like "%hello world%" or title = "%hello world%")
Run Code Online (Sandbox Code Playgroud)
或者作为
((display = 1 or display = 2) and (content like "%hello world%")) or (tags like "%hello world%" or title = "%hello world%")
Run Code Online (Sandbox Code Playgroud)
等等
Gar*_*het 30
MySQL文档有一个很好的页面,其中包含哪些运算符优先的信息.
从那页,
12.3.1.运营商优先权
运算符优先级显示在以下列表中,从最高优先级到最低优先级.一行显示的运算符具有相同的优先级.
Run Code Online (Sandbox Code Playgroud)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%"
Run Code Online (Sandbox Code Playgroud)
将被解释为
Select
*
from tablename
where
(display = 1)
or (
(display = 2)
and (content like "%hello world%")
)
or (tags like "%hello world%")
or (title = "%hello world%")
Run Code Online (Sandbox Code Playgroud)
如有疑问,请使用括号使您的意图明确.虽然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%")
)
Run Code Online (Sandbox Code Playgroud)
运行此查询:
select 1 or 1 and 0
Run Code Online (Sandbox Code Playgroud)
如果结果为1
,则意味着优先级为:
select 1 or (1 and 0)
Run Code Online (Sandbox Code Playgroud)
如果它出来了0
,那么优先级是:
select (1 or 1) and 0
Run Code Online (Sandbox Code Playgroud)
剧透:出来了 1
也就是说,AND
s 在OR
s之前被评估,或者我喜欢说,AND 更粘。