mysql条件 or_MySQL条件or/and默认执行方式

MySQL条件or/and默认执行方式

今天突然被问到了一个问题, 在SQL表达式的where条件中, 如果 a or b and c, 执行逻辑是怎样的呢?

虽然经常使用and/or, 或者也一起用, 但为了使意义明确, 一般都会用括号括起来, 不用括号的执行逻辑倒竟真的没有注意过...

于是, 就想探索一下...

一. 虚构数据集select 0 a, 0 b, 0 c

union all

select 0, 0, 1

union all

select 0,1,0

union all

select 0,1,1

union all

select 1,0,0

union all

select 1,0,1

union all

select 1,1,0

union all

select 1,1,1

abc

000

001

010

011

100

101

110

111select a*power(2,2)+b*power(2,1)+c*power(2,0) as id,v.* from

(

select 0 a, 0 b, 0 c

union all

select 0, 0, 1

union all

select 0,1,0

union all

select 0,1,1

union all

select 1,0,0

union all

select 1,0,1

union all

select 1,1,0

union all

select 1,1,1

)v

where a=0 or b=0 and c=0

;

-- 查询结果为:

idabc

0000

1001

2010

3011

4100--调整一下a, b的顺序

select a*power(2,2)+b*power(2,1)+c*power(2,0) as id,v.* from

(

select 0 a, 0 b, 0 c

union all

select 0, 0, 1

union all

select 0,1,0

union all

select 0,1,1

union all

select 1,0,0

union all

select 1,0,1

union all

select 1,1,0

union all

select 1,1,1

)v

where b=0 or a=0 and c=0

;

-- 查询结果为:

idabc

0000

1001

2010

4100

5101

经分析, 可以发现, and的优先级是高于or的, 且是右先运算, 以where a=0 or b=0 and c=0为例,

先运行 b=0 and c=0 条件, 取出结果,

然后运行a=0条件, 取出结果, 并合并结果.

故 where a=0 or b=0 and c=0 与 where a=0 or (b=0 and c=0)是相等逻辑.

同理, a=0 or b=0 and c=0 or d=0 应与 a=0 or (b=0 and c=0) or d=0 等价,

a=0 or b=0 and c=0 and d=0 应与 a=0 or (b=0 and (c=0 and d=0)) 等价,

a=0 and b=0 or c=0 and d=0 与 (a=0 and b=0) or (c=0 and d=0)等价,

...

至此, 终于搞明白啦...

其实,在mysql官方文档里也早有说明:AND and OR may be intermixed, although AND has higher precedence than OR. If you use both operators, it is a good idea to use parentheses to indicate explicitly how conditions should be grouped

发表于:2019-09-26 17:39:24浏览(576)

评论(0)

MySQL

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用[1]:condition_value是一个占位符,表示在MySQL中可以是mysql_error_code、sqlstate_value、condition_name、SQLWARNING、NOTFOUND或SQLEXCEPTION中的任意一个。[1] 引用[2]:在MySQL中,可以使用delimiter语句来指定结束符号。默认情况下,MySQL使用分号";"作为结束符号。但是在存储过程中,会使用分号作为一段语句的结束符号,这就导致了冲突。为了解决这个问题,可以使用delimiter语句来指定一个不会冲突的结束符号,比如"$$"。[2] 引用[3]:在MySQL中,可以使用declare语句来声明变量。变量可以用来存储数据,并且可以通过赋值语句来给变量赋值。例如,可以使用declare语句声明一个整型变量e_no,并使用赋值语句给它赋值。[3] 问题: MySQL中的if或者or语句是如何使用的? 回答: 在MySQL中,可以使用if语句来进行条件判断。if语句的语法是if(condition, true_value, false_value),其中condition是一个条件表达式,true_value是在条件为真时返回的值,false_value是在条件为假时返回的值。例如,可以使用if语句来判断一个变量的值是否大于10,并根据判断结果返回不同的值。[1]另外,在MySQL中,可以使用or语句来进行逻辑或运算。or语句的语法是expression1 or expression2,其中expression1和expression2是两个逻辑表达式,只要其中一个表达式为真,整个or语句就为真。例如,可以使用or语句来判断一个变量的值是否等于1或者等于2。[1]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值