MySQL 8.0中对EXISTS、NOT EXISTS的持续优化

简介: MySQL 8.0中对EXISTS、NOT EXISTS的持续优化

MySQL在8.0.16版本之前,对 INEXISTS处理是不一样的,EXISTS只能采用子查询方式,所以执行计划中能看到DEPENDENT SUBQUERY。但可以把IN优化成semi join,优化器开关(optimizer_switch)中有几个相关的开关

loosescan=on
firstmatch=on
duplicateweedout=on
materialization=on

MySQL从8.0.16开始,增加对EXISTS的优化,和IN一样也支持自动转换成semi join

从8.0.18开始,又增加了对NOT EXISTS转变成anti join的优化

我们来看下同一个SQL在5.7版本和8.0.18版本中的不同表现

1. 测试环境

两个测试表的DDL

# t1表共有30万条记录

[root@yejr.run]> show create table t1\G
1. row **
Table: t1
Create Table: CREATE TABLE t1 (
id int unsigned NOT NULL AUTO_INCREMENT,
seq int unsigned NOT NULL DEFAULT '0',
name varchar(20) NOT NULL DEFAULT '',
x int DEFAULT NULL,
PRIMARY KEY (id),
KEY k1 (seq)
) ENGINE=InnoDB AUTO_INCREMENT=300001;

# t2表共有19条记录
[root@yejr.run]> show create table t2\G
1. row **
Table: t2
Create Table: CREATE TABLE t2 (
id int NOT NULL,
nu int DEFAULT NULL,
name varchar(20) NOT NULL DEFAULT '',
PRIMARY KEY (id)
) ENGINE=InnoDB;

数据随机填充。

2. MySQL 5.7下的执行计划及成本

5.7还不支持anti-join优化,只能是用子查询。

[root@yejr.run]> explain select * from t1 where not exists ( select 1 from t2 where t1.x = t2.nu);
+----+--------------------+-------+------+------+---------+------+--------+----------+-------------+
| id | select_type | table | type | key | key_len | ref | rows | filtered | Extra |
+----+--------------------+-------+------+------+---------+------+--------+----------+-------------+
| 1 | PRIMARY | t1 | ALL | NULL | NULL | NULL | 376310 | 100.00 | Using where |
| 2 | DEPENDENT SUBQUERY | t2 | ALL | NULL | NULL | NULL | 19 | 10.00 | Using where |
+----+--------------------+-------+------+------+---------+------+--------+----------+-------------+

[root@yejr.run]> show warnings;
+-------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Level | Code | Message |
+-------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Note | 1276 | Field or reference 'yejr.t1.x' of SELECT #2 was resolved in SELECT #1 |
| Note | 1003 | / select#1 / select yejr.t1.id AS id,yejr.t1.seq AS seq,yejr.t1.name AS name,yejr.t1.x AS x from yejr.t1 where exists(/ select#2 / select 1 from yejr.t2 where (yejr.t1.x = yejr.t2.nu)) is false |
+-------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

#该SQL耗时 1.34秒
[root@yejr.run]> select * from t1 where not exists ( select 1 from t2 where t1.x = t2.nu);
299994 rows in set (1.34 sec)

#从统计结果中的 Handler_read_rnd_next 值来看,应该是做了一次笛卡尔积扫描
[root@yejr.run]> show status like 'handl%read%';
+-----------------------+---------+
| Variable_name | Value |
+-----------------------+---------+
| Handler_read_first | 300001 |
| Handler_read_key | 300001 |
...
| Handler_read_rnd_next | 6299939 |
+-----------------------+---------+

这里要纠个偏,不少人说MySQL对子查询支持不好,实际上是因为优化器无法将这个子查询改写优化成JOIN查询。

像下面这个子查询SQL,就可以被自动优化了

[root@yejr.run]> explain select * from t1 where exists ( select nu from t2 where t1.seq=t2.nu and nu >= 10);
+----+-------------+-------+-------+---------------+------+---------+------------+------+----------+----------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+-------+---------------+------+---------+------------+------+----------+----------------------------------------+
| 1 | SIMPLE | t2 | range | nu | nu | 4 | NULL | 17 | 111.76 | Using where; Using index; LooseScan |
| 1 | SIMPLE | t1 | ref | k1 | k1 | 4 | yejr.t2.nu | 1 | 100.00 | Using join buffer (Batched Key Access) |
+----+-------------+-------+-------+---------------+------+---------+------------+------+----------+----------------------------------------+
2 rows in set, 2 warnings (0.00 sec)

[root@yejr.run]> show warnings;
| Level | Code | Message |
| Note | 1276 | Field or reference 'yejr.t1.seq' of SELECT #2 was resolved in SELECT #1 |
| Note | 1003 | / select#1 / select `yejr`.`t1`.`id` AS `id`,`yejr`.`t1`.`seq` AS `seq`,`yejr`.`t1`.`name` AS `name`,`yejr`.`t1`.`x` AS `x` from `yejr`.`t1` semi join (`yejr`.`t2`) where ((`yejr`.`t1`.`seq` = `yejr`.`t2`.`nu`) and (`yejr`.`t2`.`nu` >= 10)) |
+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

3. MySQL 8.0.19下的执行计划及成本

这时支持对anti-join的优化,优化器会对SQL进行改写优化。

[root@yejr.run]> explain select * from t1 where not exists ( select 1 from t2 where t1.x = t2.nu);
+----+--------------+-------------+--------+---------------------+---------------------+---------+-----------------+--------+----------+-------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+--------------+-------------+--------+---------------------+---------------------+---------+-----------------+--------+----------+-------------------------+
| 1 | SIMPLE | t1 | ALL | NULL | NULL | NULL | NULL | 376310 | 100.00 | NULL |
| 1 | SIMPLE | <subquery2> | eq_ref | <auto_distinct_key> | <auto_distinct_key> | 5 | zhishutang.t1.x | 1 | 100.00 | Using where; Not exists |
| 2 | MATERIALIZED | t2 | ALL | NULL | NULL | NULL | NULL | 19 | 100.00 | NULL |
+----+--------------+-------------+--------+---------------------+---------------------+---------+-----------------+--------+----------+-------------------------+
3 rows in set, 2 warnings (0.00 sec)

#直接优化成anti join了
[root@yejr.run]> show warnings;
+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Level | Code | Message |
+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Note | 1276 | Field or reference 'yejr.t1.x' of SELECT #2 was resolved in SELECT #1 |
| Note | 1003 | / select#1 / select yejr.t1.id AS id,yejr.t1.seq AS seq,yejr.t1.name AS name,yejr.t1.x AS x from yejr.t1 anti join (yejr.t2) on((<subquery2>.nu = yejr.t1.x)) where true |
+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

# explain analyze结果
[root@yejr.run]> explain analyze select * from t1 where not exists ( select 1 from t2 where t1.x = t2.nu);
| -> Nested loop anti-join (actual time=0.058..248.704 rows=299994 loops=1)
-> Table scan on t1 (cost=37975.50 rows=376310) (actual time=0.035..82.504 rows=300000 loops=1)
-> Single-row index lookup on <subquery2> using <auto_distinct_key> (nu=t1.x) (actual time=0.000..0.000 rows=0 loops=300000)
-> Materialize with deduplication (actual time=0.000..0.000 rows=0 loops=300000)
-> Filter: (t2.nu is not null) (cost=2.15 rows=19) (actual time=0.006..0.011 rows=19 loops=1)
-> Table scan on t2 (cost=2.15 rows=19) (actual time=0.005..0.009 rows=19 loops=1)

#该SQL耗时 0.15 秒
[root@yejr.run]> select * from t1 where not exists ( select 1 from t2 where t1.x = t2.nu);
299994 rows in set (0.15 sec)

[root@yejr.run]> show status like 'handl%read%';
+-----------------------+--------+
| Variable_name | Value |
+-----------------------+--------+
| Handler_read_first | 2 |
| Handler_read_key | 200574 |
...
| Handler_read_rnd_next | 300021 |

相对于5.7的性能有了很大提升。

4. 一个小小的脑洞

测试过程中我突发奇想,在MySQL 8.0.19版本下,如果把oiptimizer_switch里的semijoin关闭后,应该也相当于关闭anti join优化

用EXPLAIN ANALYZE再查看这个SQL的执行计划及耗时,结果是这样的

| -> Filter: exists(select #2)  (cost=37975.50 rows=376310) (actual time=54.977..1976.963 rows=6 loops=1)
-> Table scan on t1 (cost=37975.50 rows=376310) (actual time=0.054..70.366 rows=300000 loops=1)
-> Select #2 (subquery in condition; dependent)
-> Limit: 1 row(s) (actual time=0.006..0.006 rows=0 loops=300000)
-> Filter: (t1.x = t2.nu) (cost=0.44 rows=2) (actual time=0.006..0.006 rows=0 loops=300000)
-> Table scan on t2 (cost=0.44 rows=19) (actual time=0.002..0.004 rows=19 loops=300000)

看起来的确如此。在8.0.19中,也修复了松华老师之前在8.0.18版本遇到的小bug。

最后提醒大家不要轻易关闭 semijoin 开关,以防连 anti-join 优化也跟着消失,这就不划算了。

MySQL优化器的确在不断进步中,欣慰,也建议大家适时更新到高版本。

参考:

全文完。

            </div>
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
SQL 存储 关系型数据库
MySQL主从复制之原理&一主一从部署流程—2023.04
MySQL主从复制之原理&一主一从部署流程—2023.04
1801 0
|
移动开发 JavaScript 前端开发
游戏框架 - 描述Phaser、Three.js等JavaScript游戏框架的核心功能和使用场景。
Phaser是开源2D游戏引擎,适合HTML5游戏,内置物理引擎和强大的图形渲染功能,适用于2D游戏,如消消乐。Three.js是基于WebGL的3D库,用于创建和显示3D图形,支持交互和多种3D效果,广泛应用在游戏、可视化等多个领域。两者各有侧重,选择取决于项目需求和图形交互要求。
600 3
|
存储 SQL Java
Java8 stream 中利用 groupingBy 进行多字段分组求和
Java8 stream 中利用 groupingBy 进行多字段分组求和
|
3月前
|
JSON Dubbo 网络协议
1.Dubbo(缺省默认)
Dubbo缺省协议采用单一长连接和NIO异步通信,适合小数据量高并发场景,消费者多于提供者。不适用于大数据传输,如文件或视频,除非请求量低。支持多种传输器、序列化方式和线程池策略。特性包括基于Mina和Hessian的交互、单连接、长连接、TCP传输、NIO异步、Hessian序列化等。适用于常规远程服务调用,但参数和返回值需实现Serializable接口,不能自定义集合类。配置灵活,支持多端口和连接数控制,保障服务提供者的稳定性。
1.Dubbo(缺省默认)
|
关系型数据库 MySQL 数据库
MySQL新增字段报错:ERROR 1118 -- Row size too large. The maximum row size for the used table type
MySQL新增字段报错:ERROR 1118 -- Row size too large. The maximum row size for the used table type
2137 0
|
10月前
|
关系型数据库 MySQL 数据库
Docker下Mysql8数据备份与恢复
通过以上步骤,您可以在Docker环境下高效地备份和恢复MySQL 8数据库。备份数据时,使用 `mysqldump`工具生成逻辑备份文件,并存储到指定目录;恢复数据时,使用 `mysql`工具从备份文件中读取数据并恢复到数据库。自动化脚本和定时任务的配置可以进一步简化备份和恢复的管理过程。
836 41
|
6月前
|
关系型数据库 MySQL 网络安全
MySQL 深潜 - X-plugin的传输协议
文章详细解析了X protocol的认证方式(如PLAIN、MYSQL41等)、协议格式及连接建立过程,包括服务端初始化、任务调度、请求处理等关键步骤,并结合代码示例说明认证流程。
|
SQL 监控 关系型数据库
使用 pt-query-digest 工具分析 MySQL 慢日志
【8月更文挑战第5天】使用 pt-query-digest 工具分析 MySQL 慢日志
896 3
使用 pt-query-digest 工具分析 MySQL 慢日志
|
Java Nacos 开发工具
【Nacos】心跳断了怎么办?!8步排查法+实战代码,手把手教你解决Nacos客户端不发送心跳检测问题,让服务瞬间恢复活力!
【8月更文挑战第15天】Nacos是一款广受好评的微服务注册与配置中心。然而,“客户端不发送心跳检测”的问题时有发生,可能导致服务实例被视为离线。本文介绍如何排查此类问题:确认Nacos服务器地址配置正确;检查网络连通性;查看客户端日志;确保Nacos SDK版本兼容;调整心跳检测策略;验证服务实例注册状态;必要时重启应用;检查影响行为的环境变量。通过这些步骤,通常可定位并解决问题,保障服务稳定运行。
937 0
|
Java 关系型数据库 MySQL
NUL (NULL) - ASCII值0 (0x00)
NUL (NULL) - ASCII值0 (0x00)
1972 2