mysql或/和优先级?

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

我想知道or/and是如何工作的?
例如,如果我想得到display=1的所有行
我能做到的 WHERE tablename.display = 1 如果我想要显示为1或2的所有行
我能做到的 WHERE tablename.display = 1 or tablename.display = 2 但是如果我想得到display=1或2以及任何内容、标记或标题包含的所有行,该怎么办 hello world 这样的逻辑会是怎样的呢?

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

我猜是吧。但我可以从几个方面来理解。
它是否读作:

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

或作为

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

等。

pexxcrt2

pexxcrt21#

mysql文档有一个很好的页面,上面有关于哪些操作符优先的信息。
从那一页开始,
12.3.1. 运算符优先级
运算符优先顺序显示在下面的列表中,从最高优先顺序到最低优先顺序。在一行上同时显示的运算符具有相同的优先级。

  1. INTERVAL
  2. BINARY, COLLATE
  3. !
  4. - (unary minus), ~ (unary bit inversion)
  5. ^
  6. * , /, DIV, %, MOD
  7. -, +
  8. <<, >>
  9. &
  10. |
  11. = (comparison), <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN
  12. BETWEEN, CASE, WHEN, THEN, ELSE
  13. NOT
  14. &&, AND
  15. XOR
  16. ||, OR
  17. = (assignment), :=

所以你最初的查询

  1. Select
  2. *
  3. from tablename
  4. where
  5. display = 1
  6. or display = 2
  7. and content like "%hello world%"
  8. or tags like "%hello world%"
  9. or title = "%hello world%"

会被解释为

  1. Select
  2. *
  3. from tablename
  4. where
  5. (display = 1)
  6. or (
  7. (display = 2)
  8. and (content like "%hello world%")
  9. )
  10. or (tags like "%hello world%")
  11. or (title = "%hello world%")

当你有疑问时,用括号把你的意图说清楚。虽然mysql页面上的信息很有用,但是如果再次访问查询,可能不会立即发现。
你可以考虑下面这样的事情。请注意,我已更改 title = "%hello world%"title like "%hello world%" ,因为这更符合你描述的目标。

  1. Select
  2. *
  3. from tablename
  4. where
  5. (
  6. (display = 1)
  7. or (display = 2)
  8. ) and (
  9. (content like "%hello world%")
  10. or (tags like "%hello world%")
  11. or (title like "%hello world%")
  12. )
展开查看全部
e1xvtsh3

e1xvtsh32#

运行此查询:

  1. select 1 or 1 and 0

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

  1. select 1 or (1 and 0)

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

  1. select (1 or 1) and 0

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

m1m5dgzv

m1m5dgzv3#

你需要用括号来表示你的复数 OR 条件。以及 display = 1 OR display = 2 你可以用 display IN(1,2) . 试试这个:

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

有关更多信息,请参阅mysql:operator precedence

2wnc66cl

2wnc66cl4#

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

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

顺便说一句 (display = 1 or display = 2) 相当于 display in (1, 2) .

相关问题