通过慢日志获取慢sql
-- 慢查询日志是否开启
show variables like "slow_query_log";
-- 慢sql的时间定义
show variables like 'slow_launch_time';
-- 慢日志输出方式FILE/TABLE
show variables like 'slow_query_log_file';
set可以设置如上变量。
慢sql的文件地址在slow_query_log_file,可以直接查看。
注:推荐一款慢日志分析工具:pt-query-digest
分析慢sql
profiling
show variables like '%profiling%';
set profiling=1; 打开profiling
执行你从慢日志中看到的语句
show profiles;
show profile ALL for query 10; 10为show profiles中慢sql的执行id
profiling可以看到sql执行的全过程,和各个环节的时间耗费,方便定位问题
2. explain 执行计划
explain 慢sql语句; 查看sql的执行计划
执行计划中各字段的含义
type:访问方式 (最重要)
性能越靠下越高
ALL 全表扫描
index 全索引表扫描
range 索引进行范围扫描
index_merge 合并索引,使用多个单列索引扫描
ref_or_null
ref 非唯一索引扫描
eq_ref 唯一索引扫描
system
const
NULL
table:正在访问的表名
possible_keys:可能使用的索引
key_len:MySQL中使用索引字节长度
rows:预估为了找到所需的行而要读取的行数
select_type: 解释 示例sql
simple 简单的select select * from tb_student
primary 需要union或者子查询 select (select name from tb_student where id =1) from tb_student
union union操作 select * from tb_student union select * from tb_student
dependent union 查询与外部相关(mysql优化器会将in优化成exists) select * from tb_student where id in(select id from tb_student union select id from tb_student) select * from tb_student a where EXISTS (select 1 from tb_student where id = a.id union select id from tb_student where id = a.id)
union result union结果集 select * from tb_student union select * from tb_student
subquery 除了from包含的子查询 select (select name from tb_student where id =1) from tb_student
depend subquery 类似depend union select (select name from test.tb_student a where a.id=b.id) from test.tb_student b
derived 派生表 select * from (select * from tb_student) t