这是一套可直接上手的排查方案,从发现问题到定位根因,再到优化落地,覆盖全链路。
第一步:确认慢查询是否存在
1.1 开启慢查询日志
-- 查看当前状态 show variables like 'slow_query%'; show variables like 'long_query_time'; -- 临时开启(重启失效) set global slow_query_log = on; set global long_query_time = 1; -- 超过1秒记录 set global log_queries_not_using_indexes = on;
1.2 查看慢查询数量与内容
# 统计慢查询次数 show global status like '%slow_queries%'; # 查看最近慢查询日志文件路径 show variables like 'slow_query_log_file';
第二步:分析慢查询语句
2.1 使用 explain 分析执行计划
explain select * from orders where status = 1 order by created_at desc limit 100;
重点关注字段:
| 字段 | 危险信号 |
|---|---|
type | all(全表扫描)、index(索引全扫) |
rows | 远大于预期返回行数 |
extra | using filesort(文件排序)、using temporary(临时表) |
2.2 使用 show profile 查看耗时分布
-- 开启 profiling set profiling = 1; -- 执行你的慢查询 select * from orders where ...; -- 查看所有查询的耗时 show profiles; -- 查看具体某个 query_id 的详细耗时 show profile for query 1;
关键看 sending data、sorting result、creating tmp table 等步骤的耗时占比。
第三步:常见原因与对应解决方案
3.1 没走索引 → 加索引
-- 检查是否有可用索引 show index from orders; -- 添加复合索引(注意字段顺序:等值条件在前,范围条件在后) alter table orders add index idx_status_created (status, created_at);
3.2 索引失效 → 改写 sql
常见导致索引失效的操作:
- 对索引列使用函数:
where date(created_at) = '2024-01-01' - 隐式类型转换:
where user_id = '123'(user_id 是 int) - 前导模糊匹配:
where name like '%张三'
3.3 数据量过大 → 分页优化 / 归档
深分页优化示例:
-- 原始写法(越往后越慢) select * from orders order by id limit 100000, 20; -- 优化写法(子查询用覆盖索引) select * from orders where id > (select id from orders order by id limit 100000, 1) order by id limit 20;
数据归档: 将历史数据迁移到归档表或分区表。
3.4 锁等待 → 排查锁冲突
-- 查看当前正在等待锁的事务 select * from information_schema.innodb_trx\g -- 查看锁等待关系 select * from sys.schema_table_lock_waits; -- 强制结束阻塞事务(慎用) kill [trx_mysql_thread_id];
3.5 sql 写得烂 → 重写
典型坏写法:
select *→ 只取需要的列- 子查询嵌套过深 → 改用 join 或临时表
or条件 → 拆成 union all- 循环查询 → 批量查询 + in
第四步:系统层面排查
4.1 查看数据库配置是否合理
-- 关键参数检查 show variables like 'innodb_buffer_pool_size'; -- 建议设为内存的60%-70% show variables like 'tmp_table_size'; -- 临时表大小限制 show variables like 'max_connections'; -- 连接数是否过高
4.2 查看服务器资源
# cpu、内存、io 情况 top iostat -x 1 free -h
如果 cpu 高但 io 低 → sql 计算量大或索引不合理
如果 io 高但 cpu 低 → 磁盘瓶颈,考虑 ssd 或增加 buffer pool
第五步:建立长效机制
5.1 定期巡检脚本
-- 查询当前运行时间最长的sql select * from information_schema.processlist where command != 'sleep' order by time desc limit 10; -- 查询全表扫描次数最多的表 select * from sys.schema_unused_indexes;
5.2 监控告警
- 设置
long_query_time = 1,持续采集慢查询日志 - 使用 percona toolkit 的
pt-query-digest分析日志规律 - 接入 prometheus + grafana 监控 qps、慢查询数量趋势
一句话总结排查思路
先确认慢在哪(日志+profile),再看为什么慢(explain+索引),最后对症下药(加索引/改sql/扩资源)。
到此这篇关于mysql中慢查询排查的完整流程详解的文章就介绍到这了,更多相关mysql慢查询内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论