当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL中 and or 查询的优先级

MySQL中 and or 查询的优先级

2018年12月21日  | 移动技术网IT编程  | 我要评论
这个可能是容易被忽略的问题,首选我们要清楚:MySQL中,AND的执行优先级高于OR。也就是说,在没有小括号()的限制下,总是优先执行AND语句,再执行OR语句。比如: 来点事例深入理解下:测试表数据: 查询方式1: 上面的查询等价于: 那么上面的查询结果就很好理解了。查询方式2: 上面的查询等价于 ...

这个可能是容易被忽略的问题,首选我们要清楚:
mysql中,and的执行优先级高于or。也就是说,在没有小括号()的限制下,总是优先执行and语句,再执行or语句。
比如:

select * from table where  条件1 and 条件2 or 条件3
等价于
select * from table where  ( 条件1 and 条件2 )  or 条件3

select * from table where  条件1 and  条件2 or 条件3 and 条件4
等价于
select * from table where (  条件1 and  条件2  ) or (  条件3 and 条件4  ) 

来点事例深入理解下:
测试表数据:

set names utf8mb4;
set foreign_key_checks = 0;

-- ----------------------------
-- table structure for book
-- ----------------------------
drop table if exists `book`;
create table `book`  (
  `id` int(10) unsigned not null auto_increment,
  `name` varchar(25) character set utf8mb4 collate utf8mb4_0900_ai_ci default null,
  `author` varchar(25) character set utf8mb4 collate utf8mb4_0900_ai_ci default null,
  `price` decimal(10, 2) default null,
  primary key (`id`) using btree
) engine = innodb character set = utf8mb4 collate = utf8mb4_0900_ai_ci row_format = dynamic;

-- ----------------------------
-- records of book
-- ----------------------------
insert into `book` values (1, 'php', 'mate', 21.00);
insert into `book` values (2, 'java', 'kaven', 23.00);
insert into `book` values (3, 'java高级', 'loose', 45.00);
insert into `book` values (4, 'go', 'jim', 46.00);
insert into `book` values (5, 'go设计', 'json', 76.00);
insert into `book` values (6, 'php高级编程', 'bate', 67.00);
insert into `book` values (7, 'python', 'jim', 66.00);
insert into `book` values (8, 'python设计', 'mali', 54.00);
insert into `book` values (9, 'go编程', 'kaven', 86.00);
insert into `book` values (11, 'python3', 'jim', 55.00);

set foreign_key_checks = 1;

查询方式1:

select * from book where author='jim' or author='json' and name='php';

上面的查询等价于:

select * from book where author='jim' or (author='json' and name='php');

那么上面的查询结果就很好理解了。
查询方式2:

select * from book where name='php' and author='jim' or author='json';

上面的查询等价于:

select * from book where (name='php' and author='jim') or author='json';

查询方式3:

select * from book where name='go' and (author='jim' or author='json');

这个就很好理解了。了解and or的优先级。这些查询也就不是呢么"理解混淆"了。

 

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网