2.执行计划(explain)分析

1.使用场景

获取执行计划命令:在select 命令前加上explain 或 desc

explain select 或
desc select

1.语句执行之前 :防患于未然
2.出现慢语句时 :亡羊补牢

2. 执行计划查看

3.重点关注指标说明

table :         发生在那张表的执行计划
type  :     查询的类型
                    全表扫描 : ALL
                    索引扫描 :idnex,range,ref,eq_ref,connst(system),NULL        *****
        
possible_keys:  可能用到的索引
key    :        此次查询走的索引名
key_len :       索引覆盖长度,评估联合索引应用长度。                            *****
rows  :         扫描了表中的多少行
Extra :         额外的一些信息                                                ****

4. type

2.4 type 
(1) ALL       :  全表扫描 
mysql> desc select * from city;
mysql> desc select * from city where 1=1 ;
mysql> desc select * from city where population=42;
mysql> desc select * from city where countrycode !='CHN';
mysql> desc select * from city where countrycode not in ('CHN','USA');
mysql> desc select * from city where countrycode like '%CH%';


(2) index     : 全索引扫描 
mysql> desc select countrycode from city;

(3) range     : 索引范围扫描(最常见)
>   <   >=  <=  like  
in or

mysql> desc select  *  from city where id<10;
mysql> desc select * from city where countrycode like 'CH%';


mysql> desc select * from city where countrycode  in ('CHN','USA');

改写: 

desc 
select * from city where countrycode='CHN'
union all 
select * from city where countrycode='USA'

(4) ref  辅助索引等值查询
desc 
select * from city where countrycode='CHN';


(5) eq_ref 多表关联查询中,非驱动表的连接条件是主键或唯一键
desc 
select 
city.name,
country.name ,
city.population 
from city 
join country 
on city.countrycode=country.code
where city.population<100;

(6) connst(system) :主键或者唯一键等值查询
mysql> desc select * from city where id=10;


(7) NULL  索引中获取不到数据 
mysql> desc select * from city where id=100000;
  • 在实际生产中我们尽量避免,全表扫描,全索引扫描,以及索引范围扫描,以提高查询效率,和减少资源使用。
  • 我们在多表关联查询当中,最好保证非驱动表为主键或者是唯一键,最不济为普通主键,以高效率

猜你喜欢

转载自www.cnblogs.com/yangxiaoni/p/12084603.html