mysql left join快速转inner join的过程

时间:2022-08-28 16:53:09

在日常优化过程中,发现一个怪事情,同一个sql出现两个完全不一样执行计划,left join 连驱动表都可以变成不一样。

mysql left join快速转inner join的过程

mysql left join快速转inner join的过程

对于left join,如果where条件里有被关联表过滤,left join有可能被转成inner join ,本案例中shopinfo有shopcategory = 'loc'过滤条件; 保证shopinfo的记录非null,因此left join在优化过程中可以转为inner join。 那么o和s的join顺序就是可以交换的。

验证结论:

创建表:

?
1
2
3
4
5
6
7
--班级表
create table t_class(
  class_id int not null,
  class_name varchar2(100)
);
添加索引
alter table t_class add index inx_class_id(class_id);
?
1
2
3
4
5
6
7
8
9
10
--学生表
create table t_student(
  student_id int not null,
  class_id int not null,
  student_name varchar(100),
  age int,
  sex int
)
添加索引
alter table t_student add index index_age(age);
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
--班级数据
insert into t_class (class_id, class_name)
values (1, '一班');
 
insert into t_class (class_id, class_name)
values (2, '二班');
 
insert into t_class (class_id, class_name)
values (3, '三班');
 
insert into t_class (class_id, class_name)
values (4, '四班');
 
insert into t_class (class_id, class_name)
values (5, '五班');
?
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
31
32
33
34
35
36
37
38
39
--学生数据
insert into t_student (student_id, class_id, student_name, age, sex)
values (1, 1, '李1', 3, '1');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (2, 1, '李2', 2, '1');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (3, 1, '李3', 3, '1');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (4, 2, '李4', 4, '1');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (5, 2, '李5', 3, '2');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (6, 2, '李6', 3, '1');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (7, 3, '李7', 6, '2');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (8, 3, '李8', 4, '2');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (9, 2, '李9', 2, '2');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (10, 2, '李10', 3, '1');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (11, 3, '李11', 3, '2');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (12, 2, '李12', 8, '2');
 
insert into t_student (student_id, class_id, student_name, age, sex)
values (13, 1, '李13', 6, '2');

案例1:b表有where条件且不为null

mysql left join快速转inner join的过程

案例2: a表和b表均有where条件且不为null

mysql left join快速转inner join的过程

案例3:a表和b表均有where条件且不为null,删除b表索引

mysql left join快速转inner join的过程

结论:

left join 只有被关联表有where条件,且其过滤条件优于关联表的情况下,mysql优化器才转成inner join.

到此这篇关于mysql left join快速转inner join的过程的文章就介绍到这了,更多相关mysql left join inner join内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/fulu/p/14914753.html