在特定的业务场景下,你刚开始的SQL可能就需要加force index

2024年 3月 14日 49.2k 0

今天在生产环境上遇到一个SQL 明明join表的关联字段上有索引,MySQL就是不走,由于版本又是8.0.13之前的版本。没有hash join 只能走BNL 让整个SQL奇慢无比
执行计划是这样的

执行需要93S 非常非常慢
但实际我在关联字段上不仅有索引,而且两表关联关系是1对1的。
我加了force index后 执行只需要 1.47S

为了弄清楚原因。我在测试环境进行了数据构造进行重现
构造测试数据

create table test1
(
table_schema varchar(50),
tablename varchar(200),
ver int,
id int primary key
);

create table test2
(
table_schema varchar(50),
tablename varchar(200),
ver int,
fromid int,
id int primary key
);

set @i:=0;
insert into test1(table_schema,tablename,ver,id)
select a.table_schema,a.table_name,a.version ,@i := @i+ 1 as id
from information_schema.tables a, information_schema.tables b;

set @i:=0;
insert into test2(table_schema,tablename,ver,id)
select a.table_schema,a.table_name,a.version ,@i := @i+ 1 as id
from information_schema.tables a, information_schema.tables b;

update test2 set fromid = 0;
update test2 set fromid = id where mod(id,2000000)= 0;

alter table test2 add index idx_fromid(fromid);
analyze table test2;

explain
select * from test1 a
left join test2 b on a.id = b.fromid
where a.id

相关文章

Oracle如何使用授予和撤销权限的语法和示例
Awesome Project: 探索 MatrixOrigin 云原生分布式数据库
下载丨66页PDF,云和恩墨技术通讯(2024年7月刊)
社区版oceanbase安装
Oracle 导出CSV工具-sqluldr2
ETL数据集成丨快速将MySQL数据迁移至Doris数据库

发布评论