开发者社区 问答 正文

MySQL或/和优先级?

我想知道如何或/和如何工作?

例如,如果我想获取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%") 等等

展开
收起
保持可爱mmm 2020-05-10 20:54:15 415 分享 版权
1 条回答
写回答
取消 提交回答
  • 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%") )来源:stack overflow

    2020-05-10 20:54:33
    赞同 展开评论