MySQL 性能分析

1、查询执行频次

数据库优化需要有针对性,通过查询执行频次,可以了解该数据库的执行特点(是查询多,还是增删改比较多)

-- 查询执行频次
show session/global status like 'com_______'  -- (7个空格)
variavle_name  value
----------------------
Com_binlog	  0
Com_commit    0
Com_delete	  0
Com_import	  0
Com_insert	  0
Com_repair	  0
Com_revoke	  0
Com_select	  13
Com_signal	  0
Com_update	  0
Com_xa_end	  0

2、慢查询日志(slow_query_log)

该日志记录了执行时间超过 long_query_time(seconds)的所有SQL语句的日志

开启slow_query_log功能,只需要在/etc/mysql.cnf中配置如下信息:

# 慢查询日志开关
slow_query_log = 1;  
# 或在MySQL控制台使用 SET GLOBAL slow_query_log = 'ON';

# 指定日志保存位置
slow_query_log_file = "D:/mysql-logs/slow.log" 

# 超过多少秒视为慢查询
long_query_time = 2;

# 可选,记录未使用索引的查询
log_queries_not_using_indexes = 0
# 查看MySQL配置文件 my.ini 或 my.cnf 位置
mysqld --verbose --help | more

查询是否已经开启慢查询功能:

SHOW VARIABLES LIKE 'slow_query_log';

查询日志文件名称:

SHOW VARIABLES LIKE 'slow_query_log_file';
# Time: 2025-06-30T10:25:43.123456Z
# User@Host: root[root] @ localhost []
# Thread_id: 12  Schema: test_db  QC_hit: No
# Query_time: 2.345678  Lock_time: 0.000123  Rows_sent: 100  Rows_examined: 10000
SET timestamp=1688125543;
SELECT * FROM large_table WHERE some_column = 'value' ORDER BY created_at DESC LIMIT 100;

3、profile分析

-- 查询是否支持 profile 功能
SHOW VARIABLES LIKE 'have_profiling';  -- 等价于 select @@have_profiling;

-- 查询是否开启 profile 功能
SHOW VARIABLES LIKE 'profiling';  -- 等价于 select @@profiling;

-- 针对当前会话(session)开启 profile 功能
SET profiling = 1;

-- 注意,没有下面这个配置!!(MySQL 不支持全局开启 profiling,将其限制在 session 级别)
SET GLOBAL profiling = 1;

-- 查看 profiles 执行日志
SHOW profiles;

-- 查看指定 query_id 的 SQL 语句各个阶段的耗时情况
show profiles for query query_id;

-- 查看指定 query_id 的 SQL 语句 CPU 的耗时情况
show profiles cpu for query query_id;

4、explain 执行计划

EXPLAIN 用于分析 SQL 查询的执行计划,显示查询如何访问数据、使用的索引及扫描行数等细节,帮助识别性能瓶颈;常用于 SELECTUPDATEDELETE 等语句,通过 EXPLAIN SELECT 语法查看查询优化建议,MySQL 8.0+ 还支持 EXPLAIN ANALYZE 提供实际执行时间。

 

 

 

 

 

 

 

 

 

This article was updated on