MySQL中怎么分析性能?

news/2025/3/25 2:06:57/文章来源:https://www.cnblogs.com/huajieyu/p/18787824

MySQL中主要有4种方式可以分析数据库性能,分别是慢查询日志,profile,Com_xxx和explain。

慢查询日志

先用下面命令查询慢查询日志是否开启,

show variables like 'slow_query_log';# 一般默认都是以下结果
+----------------+-------+
| Variable_name  | Value |
+----------------+-------+
| slow_query_log | OFF   |
+----------------+-------+
  • 若结果为 ON,表示慢查询日志已开启;若为 OFF,则需要手动开启。但是一般慢查询日志是默认不开启的,需要手动开启,因为需要指定指标,也就是多慢的SQL才算慢SQL。

临时开启(重启 MySQL 后失效):

# 开启慢查询日志
set global slow_query_log = 'ON';
# 设置一个时间,超过这个时间的查询都会被认为是慢查询,会记录到慢查询日志里,单位是秒(s)
set global long_query_time = 2;

永久开启:

linux环境下只需要改一下/etc/my.cnf配置文件,在里面加入如下两行配置

# 0:关闭慢查询日志 1:开启慢查询日志
slow_query_log = 1  
# 指定日志文件路径(可选,不选则有默认路径)
slow_query_log_file = /var/log/mysql/slow.log
# 设置一个时间,超过这个时间的查询都会被认为是慢查询,会记录到慢查询日志里,单位是秒(s)
long_query_time = 2
# 是否记录未使用索引的查询(1表示开启,0表示关闭,默认关闭)
log_queries_not_using_indexes = 1

关键是参数【slow_query_log】和【long_query_time】一定要设置,配置完毕保存后然后使用【systemctl restart mysqld】在Linux命令行重启MySQL即可。此时慢查询的日志会记录到文件里,如果没有配置路径,使用到了默认路径,可以查询一下文件位置:

SHOW VARIABLES LIKE 'slow_query_log_file';# 得到结果可能如下
+---------------------+-------------------------------+
| Variable_name       | Value                         |
+---------------------+-------------------------------+
| slow_query_log_file | /var/lib/mysql/hostname-slow.log |
+---------------------+-------------------------------+

然后去指定目录直接查看log文件即可。


profile

使用下列命令查看profiling是否开启

show variables like 'profiling';# 默认是关闭的,一般查询结果如下
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| profiling     | OFF   |
+---------------+-------+

需要手动开启。

临时开启profiling(重启 MySQL 后失效):

在SQL执行窗口设定参数

set profiling = 1;

永久开启:

在/etc/my.cnf文件中加入如下配置

profiling = 1

要记得修改过/etc/my.cnf文件以后要重启mysql。

此时随便执行几条sql,然后再来查询一下profile。

# 此时为了测试我创建了一个表
# 执行下面几条查询
select * from test where id = 2;
select * from test where id = 1;
select * from test;# 执行下行语句,查询Query记录
show profiles;
# 得到如下结果,Query列是查询语句,Duration是执行消耗的时间,Query_ID是记录ID
+----------+------------+------------------------------------+
| Query_ID | Duration   | Query                              |
+----------+------------+------------------------------------+
|        1 | 0.00029275 | select * from test where id = 2    |
|        2 | 0.00022375 | select * from test where id = 1    |
|        3 | 0.00020425 | select * from test                 |
+----------+------------+------------------------------------+# 如果想要对某一条SQL进行分析,比如这里Query_ID为1的记录消耗时间最长,想要看一下具体情况,可以使用如下命令
show profile for query 1;# 得到如下结果
+--------------------------------+----------+
| Status                         | Duration |
+--------------------------------+----------+
| starting                       | 0.000115 |
| Executing hook on transaction  | 0.000008 |
| starting                       | 0.000009 |
| checking permissions           | 0.000005 |
| Opening tables                 | 0.000037 |
| init                           | 0.000004 |
| System lock                    | 0.000007 |
| optimizing                     | 0.000009 |
| statistics                     | 0.000045 |
| preparing                      | 0.000011 |
| executing                      | 0.000009 |
| end                            | 0.000002 |
| query end                      | 0.000002 |
| waiting for handler commit     | 0.000007 |
| closing tables                 | 0.000007 |
| freeing items                  | 0.000010 |
| cleaning up                    | 0.000007 |
+--------------------------------+----------+# 可以看到开始时间,执行时间,打开表的时间,优化时间,准备时间,关闭表的时间等参数
# 如果SQL查询很慢的话则可以从这里分析原因

Com_%

# 执行下列命令
show status like 'Com_%'; # 得到结果格式如下
+-------------------------------------+-------+
| Variable_name                       | Value |
+-------------------------------------+-------+
| Com_admin_commands                  | 0     |
| Com_assign_to_keycache              | 0     |
| Com_alter_db                        | 0     |
| Com_alter_event                     | 0     |
| Com_alter_function                  | 0     |
| Com_alter_instance                  | 0     |
| Com_alter_procedure                 | 0     |
| Com_alter_resource_group            | 0     |
| Com_alter_server                    | 0     |
| Com_alter_table                     | 0     |
| Com_alter_tablespace                | 0     |
| Com_alter_user                      | 0     |
| Com_alter_user_default_role         | 0     |
| Com_analyze                         | 0     |
| Com_begin                           | 0     |
| Com_binlog                          | 0     |
| Com_call_procedure                  | 0     |
| Com_change_db                       | 1     |
| Com_change_master                   | 0     |
| Com_change_repl_filter              | 0     |
| Com_change_replication_source       | 0     |
| Com_check                           | 0     |
| Com_checksum                        | 0     |
| Com_clone                           | 0     |
| Com_commit                          | 0     |
| Com_create_db                       | 0     |
| Com_create_event                    | 0     |
| Com_create_function                 | 0     |
| Com_create_index                    | 0     |
| Com_create_procedure                | 0     |
| Com_create_role                     | 0     |
| Com_create_server                   | 0     |
| Com_create_table                    | 0     |
| Com_create_resource_group           | 0     |
| Com_create_trigger                  | 0     |
| Com_create_udf                      | 0     |
| Com_create_user                     | 0     |
| Com_create_view                     | 0     |
| Com_create_spatial_reference_system | 0     |
| Com_dealloc_sql                     | 0     |
| Com_delete                          | 0     |
| Com_delete_multi                    | 0     |
| Com_do                              | 0     |
| Com_drop_db                         | 0     |
| Com_drop_event                      | 0     |
| Com_drop_function                   | 0     |
| Com_drop_index                      | 0     |
| Com_drop_procedure                  | 0     |
| Com_drop_resource_group             | 0     |
| Com_drop_role                       | 0     |
| Com_drop_server                     | 0     |
| Com_drop_spatial_reference_system   | 0     |
| Com_drop_table                      | 0     |
| Com_drop_trigger                    | 0     |
| Com_drop_user                       | 0     |
| Com_drop_view                       | 0     |
| Com_empty_query                     | 0     |
| Com_execute_sql                     | 0     |
| Com_explain_other                   | 0     |
| Com_flush                           | 0     |
| Com_get_diagnostics                 | 0     |
| Com_grant                           | 0     |
| Com_grant_roles                     | 0     |
| Com_ha_close                        | 0     |
| Com_ha_open                         | 0     |
| Com_ha_read                         | 0     |
| Com_help                            | 0     |
| Com_import                          | 0     |
| Com_insert                          | 0     |
| Com_insert_select                   | 0     |
| Com_install_component               | 0     |
| Com_install_plugin                  | 0     |
| Com_kill                            | 0     |
| Com_load                            | 0     |
| Com_lock_instance                   | 0     |
| Com_lock_tables                     | 0     |
| Com_optimize                        | 0     |
| Com_preload_keys                    | 0     |
| Com_prepare_sql                     | 0     |
| Com_purge                           | 0     |
| Com_purge_before_date               | 0     |
| Com_release_savepoint               | 0     |
| Com_rename_table                    | 0     |
| Com_rename_user                     | 0     |
| Com_repair                          | 0     |
| Com_replace                         | 0     |
| Com_replace_select                  | 0     |
| Com_reset                           | 0     |
| Com_resignal                        | 0     |
| Com_restart                         | 0     |
| Com_revoke                          | 0     |
| Com_revoke_all                      | 0     |
| Com_revoke_roles                    | 0     |
| Com_rollback                        | 0     |
| Com_rollback_to_savepoint           | 0     |
| Com_savepoint                       | 0     |
| Com_select                          | 8     |
| Com_set_option                      | 1     |
| Com_set_password                    | 0     |
| Com_set_resource_group              | 0     |
| Com_set_role                        | 0     |
| Com_signal                          | 0     |
| Com_show_binlog_events              | 0     |
| Com_show_binlogs                    | 0     |
| Com_show_charsets                   | 0     |
| Com_show_collations                 | 0     |
| Com_show_create_db                  | 0     |
| Com_show_create_event               | 0     |
| Com_show_create_func                | 0     |
| Com_show_create_proc                | 0     |
| Com_show_create_table               | 0     |
| Com_show_create_trigger             | 0     |
| Com_show_databases                  | 2     |
| Com_show_engine_logs                | 0     |
| Com_show_engine_mutex               | 0     |
| Com_show_engine_status              | 0     |
| Com_show_events                     | 0     |
| Com_show_errors                     | 0     |
| Com_show_fields                     | 1     |
| Com_show_function_code              | 0     |
| Com_show_function_status            | 0     |
| Com_show_grants                     | 0     |
| Com_show_keys                       | 0     |
| Com_show_master_status              | 0     |
| Com_show_open_tables                | 0     |
| Com_show_plugins                    | 0     |
| Com_show_privileges                 | 0     |
| Com_show_procedure_code             | 0     |
| Com_show_procedure_status           | 0     |
| Com_show_processlist                | 0     |
| Com_show_profile                    | 5     |
| Com_show_profiles                   | 1     |
| Com_show_relaylog_events            | 0     |
| Com_show_replicas                   | 0     |
| Com_show_slave_hosts                | 0     |
| Com_show_replica_status             | 0     |
| Com_show_slave_status               | 0     |
| Com_show_status                     | 2     |
| Com_show_storage_engines            | 0     |
| Com_show_table_status               | 0     |
| Com_show_tables                     | 2     |
| Com_show_triggers                   | 0     |
| Com_show_variables                  | 3     |
| Com_show_warnings                   | 0     |
| Com_show_create_user                | 0     |
| Com_shutdown                        | 0     |
| Com_replica_start                   | 0     |
| Com_slave_start                     | 0     |
| Com_replica_stop                    | 0     |
| Com_slave_stop                      | 0     |
| Com_group_replication_start         | 0     |
| Com_group_replication_stop          | 0     |
| Com_stmt_execute                    | 0     |
| Com_stmt_close                      | 0     |
| Com_stmt_fetch                      | 0     |
| Com_stmt_prepare                    | 0     |
| Com_stmt_reset                      | 0     |
| Com_stmt_send_long_data             | 0     |
| Com_truncate                        | 0     |
| Com_uninstall_component             | 0     |
| Com_uninstall_plugin                | 0     |
| Com_unlock_instance                 | 0     |
| Com_unlock_tables                   | 0     |
| Com_update                          | 0     |
| Com_update_multi                    | 0     |
| Com_xa_commit                       | 0     |
| Com_xa_end                          | 0     |
| Com_xa_prepare                      | 0     |
| Com_xa_recover                      | 0     |
| Com_xa_rollback                     | 0     |
| Com_xa_start                        | 0     |
| Com_stmt_reprepare                  | 0     |
| Compression                         | OFF   |
| Compression_algorithm               |       |
| Compression_level                   | 0     |
+-------------------------------------+-------+# 重点查看4个参数的值,Com_insert,Com_delete,Com_update,Com_select的参数。因为我没有执行增删改操作,所以都是0,刚刚又查询了几次记录,这边的Com_select已经到8了,代表当前已经执行过8次select操作,0次insert,0次delete,0次update。

在需要分析增删改查操作到底是增删改比较多还是查询比较多的时候可以使用这个方式查询相关记录的执行情况,分析某个业务到底是查询比较多呢还是更新比较多,从而可以更好地对系统架构进行把控。


explain

# 对需要执行的sql分析执行计划,假如要分析下面这条查询语句
select * from tb_user where id=1;# 语法如下
explain select * from test where id=1;
# 其实就是在查询语句前加上explain关键字,insert,update和delete语句前也可以加上进行分析执行计划
# 得到结果格式如下+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
| id | select_type | table   | partitions | type  | possible_keys | key     | key_len | ref   | rows | filtered | Extra |
+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | tb_user | NULL       | const | PRIMARY       | PRIMARY | 4       | const |    1 |   100.00 | NULL  |
+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
# 需要关注id列
# 相同的 id 表示同一查询块。
# id 越大,执行优先级越高。
# id 为 NULL 表示是 UNION 结果的合并操作。
# -----------------------------------------------------
# 需要关注type列,其中type列的介绍和性能如下(性能从高到低排列)
# NULL:直接查询,不进行表操作,例如select 1 + 1;
# system:表中只有一行数据(系统表)。
# const:通过主键或唯一索引查找一行数据。
# eq_ref:通过唯一索引关联表(多表 JOIN 时,每行只匹配一行)。
# ref:通过非唯一索引查找数据。
# range:使用索引范围扫描。
# index:全索引扫描(扫描索引树,不访问数据行)。
# ALL:全表扫描(性能最差)。
# -----------------------------------------------------
# 需要关注possible_keys列和key列
# possible_keys代表可能用到的索引,key就是实际用到的索引,从这里可以分析索引是不是没有用到或者失效了
# 优化的时候要尽量让没有使用到索引的语句使用索引
# -----------------------------------------------------
# 需要关注key_len
# 如果用到了单列索引,则key_len是一个固定值
# 如果用到了联合索引,key_len的值可能会因为部分索引失效而导致key_len的值不一样,可以通过这一列判断联合索引是否全部生效。
# -----------------------------------------------------
# 需要关注rows列,记录的是MySQL预估需要扫描的行数。
# 行数越少,性能越好,如果值很大,可能需要优化索引或查询条件。
# -----------------------------------------------------
# 需要关注filtered列
# filtered= Server层过滤后的行数/存储引擎层返回的行数 ×100%
# 值越小,说明存储引擎层已经过滤了更多不满足条件的数据,Server 层只需处理少量数据。
# -----------------------------------------------------
# 重点关注Extra列,其中可能出现的值如下:
# Using where:使用了 WHERE 条件过滤数据。
# Using index:使用了覆盖索引(无需回表)。
# Using temporary:使用了临时表(性能较差)。
# Using filesort:使用了文件排序(性能较差)。
# Using join buffer:使用了 JOIN 缓冲区(多表 JOIN 时)。
# Impossible WHERE:WHERE 条件永远为假(无结果)。
# 需要注意尽可能避免Using temporary和Using filesort,以及Impossible WHERE。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/904200.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!

前言 今天大姚给大家分享一款基于 .NET 开源(GPL-2.0 license)、免费、功能强大的 Windows 远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议:mRemoteNG。 项目介绍 mRemoteNG是一款基于 .NET 开源(GPL-2.0 license)、免费、功能强大的 Windows 远程连接管理工具,支…

探秘Transformer系列之(17)--- RoPE

从零开始解析Transformer,目标是:(1) 解析Transformer如何运作,以及为何如此运作,让新同学可以入门;(2) 力争融入一些比较新的或者有特色的论文或者理念,让老鸟也可以有所收获。探秘Transformer系列之(17)--- RoPE 目录探秘Transformer系列之(17)--- RoPE文章总表0x0…

《AI未来进行式》(DeepSeek、宇树科技、人形机器人、AI面试官本书全部预言。第18届文津提名奖,樊登、俞敏洪、刘慈欣等推荐) | PDF免费下载

《AI未来进行式》深入探讨人工智能的最新进展与未来趋势,涵盖 DeepSeek、宇树科技、人形机器人、AI 面试官等前沿话题。通过翔实案例与专业分析,预测 AI 如何重塑社会、产业与人类生活。荣获第18届文津图书奖提名,获樊登、俞敏洪、刘慈欣等推荐,适合对 AI 未来充满好奇的读…

python第三章课后程序练习题

重量计算 earth_weight = eval(input("请输入你当前的体重(kg)😊) moon_weight = earth_weight * 0.165 for year in range(1, 11): earth_weight += 0.5 moon_weight = earth_weight * 0.165 print(f"Year {year}: Earth weight = {earth_weight}kg, Moon weight …

逆序对的数量 与 归并排序

题目描述 给定一个长度为 n 的整数数列,请你计算数列中的逆序对的数量。 逆序对的定义如下:对于数列的第 i 个和第 j 个元素,如果满足i<j且 a[i]>a[j],则其为一个逆序对;否则不是。 输入格式 第一行包含整数 n,表示数列的长度。 第二行包含 n 个整数,表示整个数列…

我最常用的 Visual Studio 2022 扩展插件推荐:生产力必备工具

Visual Studio 2022作为微软推出的一款功能强大的IDE,业界称之为“宇宙第一IDE”。它以出色的性能、丰富的内置功能和对多种编程语言的支持,深受开发者喜爱。然而,随着项目复杂度的增加和开发需求的多样化,仅依靠IDE的内置功能往往不足以满足所有场景。这时,扩展插件成为了…

25年可以免费使用的云服务器

免费服务器:调试程序与建站的好帮手网站链接为:https://www.sanfengyun.com/ 在数字化时代,无论是个人开发者、大学生还是时间充裕的技术爱好者,拥有一台稳定的服务器来调试程序和搭建网站都是至关重要的。而正是这样一个为广大用户提供了极大便利的平台,它以其免费的云服…

Code Runner MCP Server,来了!

大家好!我是韩老师。如果作为程序员的你,还不了解 MCP (Model Context Protocol) 的话,那韩老师劝你赶紧去补补课吧!本文不对 MCP 进行详细介绍~ 简单来说,MCP is another LSP in AI World! 也许有一天,AI 程序员不懂 MCP,就犹如前端程序员不懂 JavaScript!大家都知道韩…

Ollama初识

初识ollama,学习基本功能和记录参数前言 最近由于 deepseek 的火爆,AI 大语言模型又一次被抬了出来,对此早有关注的我决定尝试本地化部署使用体验一下,并且搭建一个本地的 AI 助手。 根据我之前了解到的信息,在使用大模型,现在较为方便的方法一般是先搭建一个大模型的管理…

Pass-15

function isImage($filename){//需要开启php_exif模块$image_type = exif_imagetype($filename);switch ($image_type) {case IMAGETYPE_GIF:return "gif";break;case IMAGETYPE_JPEG:return "jpg";break;case IMAGETYPE_PNG:return "png";break…

Pass-16

$is_upload = false; $msg = null; if (isset($_POST[submit])){// 获得上传文件的基本信息,文件名,类型,大小,临时文件路径$filename = $_FILES[upload_file][name];$filetype = $_FILES[upload_file][type];$tmpname = $_FILES[upload_file][tmp_name];$target_path=UPLO…