MySQL中 and or 查询的优先级分析

吾爱主题 阅读:148 2024-04-02 08:00:40 评论:0

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

?
1 2 3 4 5 6 7 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  )

来点事例深入理解下:

测试表数据:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 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:

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

上面的查询等价于:

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

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

查询方式2:

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

上面的查询等价于:

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

查询方式3:

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

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

到此这篇关于mysql中 and or 查询的优先级分析的文章就介绍到这了,更多相关mysql and or 查询内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/phpper/p/10154627.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容