mysql 读写优先级,MySQL或/和优先级?

I am wondering how or/and works?

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

I can just do WHERE tablename.display = 1

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

I can just do WHERE tablename.display = 1 or tablename.display = 2

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

How would the logic play out for that?

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.

Does it read out as:

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

or as

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

etc.

解决方案

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

From that page,

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), :=

So your original query

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 interpreted as

Select

*

from tablename

where

(display = 1)

or (

(display = 2)

and (content like "%hello world%")

)

or (tags like "%hello world%")

or (title = "%hello world%")

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.

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

)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值