相同执行计划,为何有执行快慢的差别
- 前言
- 场景复现
- 新的技巧
- 总结
前言
今天遇到一个很神奇的现象,在数据库中,相同的执行计划,执行SQL所需要的时间相差很大,执行快的SQL瞬间出结果,执行慢的SQL要几十秒才出结果,一度让我怀疑是数据库抽风了,后面才发现是见识不足,又进入了知识空白区。
场景复现
数据库版本使用的是8.0.23 MySQL Community Server - GPL
由于生产环境数据敏感,禁止随意折腾,我在自己的测试环境,通过如下步骤,构造了一批数据,勉强能够复现出相同的场景来
- 使用sysbench构造一万张表,每张表10行记录即可。
- create table test.test_col as select * from information_schema.columns;
- create table test.test_tab as select * from information_schema.tables;
- create table test.test_tc as select * from information_schema.table_constraints;
- 执行10次 insert into test.test_tab select * from test.test_tab;
- 创建必要的索引
alter table test_col add key(table_schema, table_name);alter table test_col add key(column_name);alter table test_tab add key(table_schema, table_name);alter table test_tc add key(table_name);