Mysql优化

慢查询日志

show variables like 'slow_query_log'

show variables like '%log%'

set global log_queries_not_using_indexes=on

show variables like 'long_query_time'

set global long_query_time=1

set global slow_query_log=on

show variables like 'slow%'

set global slow_query_log_file=''

 

SQL语句优化

Max()语句优化

Max()列上创建索引

原语句:select max(payment_date) from payment;

优化:create index idx_paydate on payment(payment_date);

 

Count()语句优化

count(*)包括null值 count(具体列)不包括null值

优化:select count(release_year=’2006’ or null) as ‘2006’,

Count(release_year=’2007’ or null) as ‘2007’ from film;

 

子查询优化

将子查询改为join语句,如果存在一对多的关系,使用distinct去重

原语句:select title,release_year,length from film where film_id in(

select film_id from film_actor where actor_id in (

select actor_id from actor where first_name=’sandra’))

 

group by优化

原语句: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;

优化: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优化

排序的字段设为索引字段

原语句:select film_id,description from sakila.film order by title

limit 50,5;

优化:select film_id,description from sakila.film order by film_id

limit 50,5;

优化:select film_id,description from sakila.film where film_id>50 and

film_id<=55 order by film_id limit 1,5;

 

 

索引优化

where从句,group by从句,order by从句,on从句中的字段建立索引;

索引字段尽可能小;

联合索引中离散度大的列放在前面;

删除重复索引和无用索引;

 

表结构优化

设计表选择合适的数据类型

表的范式化和反范式化

表的垂直拆分(解决表的字段过多问题)

表的水平拆分(解决单表的数据量过多问题)

posted @ 2019-11-08 18:56  踏云逐月追风客  阅读(151)  评论(0编辑  收藏  举报