-查找慢SQL日志文件位置:
show variables like '%slow_query_log_file%';
-使用mysqldumpslow命令分析慢SQL日志
-s: 表示按何种方式排序:
c: 访问次数
l: 锁定时间
r: 返回记录
t: 查询时间
al: 平均锁定时间
ar: 平均返回记录数
at: 平均查询时间
-t: 返回前面多少条的数据;
-查询返回结果最多的10条SQL:
mysqldumpslow -s r -t 10 /usr/local/mysql/data/localhost_slow.log
-查询耗时最长的10条SQL:
mysqldumpslow -s t -t 10 /usr/local/mysql/data/localhost_slow.log
-performance_schema 库
performance_schema库帮助我们记录了MySQL的运行情况,很多性能问题都可以在performance_schema库中查到。 有哪些锁等待、加锁的SQL、正在执行的事务等。
information_schema.innodb_lock_waits 锁等待
information_schema.innodb_locks 定位锁
information_schema.innodb_trx 定位事务
performance_schema.threads 定位线程
performance_schema.events_statements_current 定位SQL
information_schema.processlist 正在执行的SQL进程
information_schema.profiling 分析SQL每一步的耗时,查询性能瓶颈
-查看锁等待情况:
select * from information_schema.innodb_lock_waits;
-查看正在竞争的锁
select * from information_schema.innodb_locks;
-查看正在执行的事务
select * from information_schema.innodb_trx;
-查看事务线程
select * from performance_schema.threads where processlist_id=193;
-查看线程正在执行的SQL语句
select THREAD_ID,CURRENT_SCHEMA,SQL_TEXT
from performance_schema.events_statements_current
where thread_id=218;
-优化查询规范
1.禁止使用select *
2.用小表驱动大表
3.join关联表不宜过多
4.禁止使用左模糊或者全模糊查询
5.索引访问类型至少达到range级别
6.更优雅的使用联合索引
7.注意避免深分页
8.单表字段不要超过30个MySQL规约
9.枚举字段不要使用字符类型
10.小数类型禁止使用float和double
11.所有字段必须设置默认值且不允许为null
12.必须创建主键,最好是有序数值类型
13.快速判断是否存在某条记录
14.in条件中数量不宜过多
15.禁止创建预留字段
16.单表索引数不要超过5个
-索引失效
如果遇到索引失效,也有可能出现慢SQL。常见的索引失效场景有如下这些:
数据类型隐式转换
模糊查询 like 以%开头
or前后没有同时使用索引
联合索引,没有使用第一列索引
在索引字段进行计算操作
在索引字段字段上使用函数
优化器选错索引
-查看死锁日志
show engine innodb status;