mysql-explain之Using temporary

今天同事问到我一个问题,说某个带有join的查询语句创建视图后,查询视图时带有order by字段时,某些字段会很快,某些会稍微慢一些。

drop view if exists test1;
create view test1 as
select a.*,b.b_info_outstandingbalance,ifnull(b.new_count,0) new_count,ifnull(b.new_amount,0) new_amount,b.adj_term_year,b.private_percent from 
blr_company_info a
inner join 
(select company_id,b_info_outstandingbalance,new_count,new_amount,adj_term_year,private_percent from blr_company_bond_info  where c_date = (select max(c_date) from blr_company_bond_info)) b
on a.company_id = b.company_id

具体创建视图sql如上面所示,其中a表大概是五千条数据,而b表大概是四千条数据,当使用原在b表中的字段做order by的时候就稍微快一些,a表中的字段做order by就稍微慢一些。
然后我就做了个测试:

a表的company_id

explain
select * from test1 order by company_id desc 

在这里插入图片描述

b表的b_info_outstandingbalance

explain
select * from test1 order by b_info_outstandingbalance desc 

在这里插入图片描述

两个explain的区别就是上面的那个用到了临时表,为什么会用到临时表,为什么只有他用到了临时表,之后又做了几个实验,发现只有join的主表中的字段进行order by的时候才不会用到临时表,而inner join的时候主表的选择方式为数据量最少的表为主表,所以b表为主表,当b表中的字段做order by的时候才不会用到临时表。
另外多说一句:left join的主表选择方式为左侧表为主表,inner join主表选择方式为数据量少的为主表,所以 left join的时候最好将数据量少的表放在左侧,这样的查询速度会更快些。

具体关于explain的解释可以移步到此处

猜你喜欢

转载自blog.csdn.net/qq_37823979/article/details/109327507
今日推荐