MySQL或/和优先级? [英] Mysql or/and precedence?

查看:101
本文介绍了MySQL或/和优先级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wondering how or/and works?

例如,如果我想获取所有display = 1的行

For example if I want to get all rows where display = 1

我可以做WHERE tablename.display = 1

,如果我希望显示= 1或2的所有行

and if I want all rows where display = 1 or 2

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

但是如果我想获得display = 1或2且任何内容,标签或标题包含hello world

But what if I want to get all rows where display = 1 or 2 and where any of the content, tags, or title contains 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%"

会是我的猜测.但是我可以通过几种方式阅读.

Would be my guess. but then I can read that in several ways.

它的读数为:

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

推荐答案

MySQL文档具有

The MySQL documentation has a good page with information on which operators take precedence.

在该页面上,

12.3.1.运算符优先级

12.3.1. Operator Precedence

运算符的优先级显示在下面的列表中,从最高优先级到最低优先级.运算符 一起显示在同一行上的优先级相同.

Operator precedences are shown in the following list, from highest precedence to the lowest. Operators that are shown together on a line have the same precedence.

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"页面上的信息很有帮助,但如果再次访问该查询,可能不会立即显而易见.

When in doubt, use parenthesis to make your intent clear. While the information on the MySQL page is helpful, it may not be immediately obvious if the query is ever revisited.

您可能会考虑以下内容.请注意,我已将title = "%hello world%"更改为title like "%hello world%",因为它更适合您描述的目标.

You might consider something like the following. Note that I've changed the title = "%hello world%" to title like "%hello world%", since that fits better with the goal you've described.

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

这篇关于MySQL或/和优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆