优化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;
上面这条sql 使用到了临时表,文件排序,因此可以进行下列改写:
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查询
limit常用于分页处理,时常会伴随order by从句使用,因此大多数时候会使用Filesorts这样会造成大量的IO问题
SELECT film_id, description FROM sakila.film ORDER BY title LIMIT 50,5;
优化步骤1:使用有索引的列或者主键进行Order by 操作
SELECT film_id, description FROM sakila.film ORDER BY film_id LIMIT 50, 5;
步骤2:记录上次返回的主键,在下次查询时使用主键过滤
SELECT film_id, description FROM sakila.film WHERE film_id > 55 and film_id <= 60 ORDER BY film_id LIMIT 1, 5;此方法避免了数据量大时扫描过多的记录