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

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: 史上最优惠活动:阿里云企业云服务器全场2折起

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;
相关文章
|
2天前
|
弹性计算 运维 搜索推荐
三翼鸟携手阿里云ECS g9i:智慧家庭场景的效能革命与未来生活新范式
三翼鸟是海尔智家旗下全球首个智慧家庭场景品牌,致力于提供覆盖衣、食、住、娱的一站式全场景解决方案。截至2025年,服务近1亿家庭,连接设备超5000万台。面对高并发、低延迟与稳定性挑战,全面升级为阿里云ECS g9i实例,实现连接能力提升40%、故障率下降90%、响应速度提升至120ms以内,成本降低20%,推动智慧家庭体验全面跃迁。
|
3天前
|
数据采集 人工智能 自然语言处理
3分钟采集134篇AI文章!深度解析如何通过云无影AgentBay实现25倍并发 + LlamaIndex智能推荐
结合阿里云无影 AgentBay 云端并发采集与 LlamaIndex 智能分析,3分钟高效抓取134篇 AI Agent 文章,实现 AI 推荐、智能问答与知识沉淀,打造从数据获取到价值提炼的完整闭环。
352 91
|
10天前
|
人工智能 自然语言处理 前端开发
Qoder全栈开发实战指南:开启AI驱动的下一代编程范式
Qoder是阿里巴巴于2025年发布的AI编程平台,首创“智能代理式编程”,支持自然语言驱动的全栈开发。通过仓库级理解、多智能体协同与云端沙箱执行,实现从需求到上线的端到端自动化,大幅提升研发效率,重塑程序员角色,引领AI原生开发新范式。
874 156
|
3天前
|
数据采集 缓存 数据可视化
Android 无侵入式数据采集:从手动埋点到字节码插桩的演进之路
本文深入探讨Android无侵入式埋点技术,通过AOP与字节码插桩(如ASM)实现数据采集自动化,彻底解耦业务代码与埋点逻辑。涵盖页面浏览、点击事件自动追踪及注解驱动的半自动化方案,提升数据质量与研发效率,助力团队迈向高效、稳定的智能化埋点体系。(238字)
258 156
|
4天前
|
域名解析 人工智能
【实操攻略】手把手教学,免费领取.CN域名
即日起至2025年12月31日,购买万小智AI建站或云·企业官网,每单可免费领1个.CN域名首年!跟我了解领取攻略吧~
|
11天前
|
机器人 API 调度
基于 DMS Dify+Notebook+Airflow 实现 Agent 的一站式开发
本文提出“DMS Dify + Notebook + Airflow”三位一体架构,解决 Dify 在代码执行与定时调度上的局限。通过 Notebook 扩展 Python 环境,Airflow实现任务调度,构建可扩展、可运维的企业级智能 Agent 系统,提升大模型应用的工程化能力。
|
人工智能 前端开发 API
前端接入通义千问(Qwen)API:5 分钟实现你的 AI 问答助手
本文介绍如何在5分钟内通过前端接入通义千问(Qwen)API,快速打造一个AI问答助手。涵盖API配置、界面设计、流式响应、历史管理、错误重试等核心功能,并提供安全与性能优化建议,助你轻松集成智能对话能力到前端应用中。
817 154