mysql或/和优先级?

7hiiyaii  于 2021-07-24  发布在  Java
关注(0)|答案(4)|浏览(353)

我想知道or/and是如何工作的?
例如,如果我想得到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%")

等。

dojqjjoe

dojqjjoe1#

mysql文档有一个很好的页面,上面有关于哪些操作符优先的信息。
从那一页开始,
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%")
    )
axkjgtzd

axkjgtzd2#

运行此查询:

select 1 or 1 and 0

如果结果是 1 ,则表示优先级为:

select 1 or (1 and 0)

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

select (1 or 1) and 0

扰流板:出来了 1 也就是说, AND 在之前评估 OR s、 或者就像我喜欢说的,AND更粘。

whlutmcx

whlutmcx3#

你需要用括号来表示你的复数 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

bq9c1y66

bq9c1y664#

在所有sql Server中, AND 优先于 OR ,所以请记住在你的 OR 学生:

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) 相当于 display in (1, 2) .

相关问题