type :
- const 常数查找,一般为主键或者唯一索引查找
- eq_reg 范围查找,主键或者唯一索引的范围查找
- ref 一般用于连接查询,一个表基于某个索引的查找
- range 基于索引的范围查找
- index 基于索引的扫描
- all 表扫描
key_len : 索引的长度,mysql 每次读取以页为单位,如果一页中存储的索引数量越大,查询效率越高
count() 和 max()的优化
子查询到优化
连接查询,如果是一对多关系,将出现多个重复结果,用 distinct 去重
group by 优化
优化前:
explain select actor.first_name,actor.last_name,count(*) from sakila.film_actor inner join sakila.actor using(actor_id) group by film_actor.actor_id
优化后:
explain select actor.first_name,actor.last_name,c.cnt from sakila.actor inner join(select actor_id,count(*) as cnt from sakila.film_actor group by actor_id) as c using(actor_id)
在子查询中用过滤条件,而不是连接之后,再用过滤
Limit 优化
优化前:
explain select film_id,description from sakila.film order by title limit 50,5
优化后:
explain select film_id,description from sakila.film order by film_id limit 50,5