search
HomeDatabaseMysql TutorialMySQL慢查询优化之慢查询日志分析的实例教程_MySQL

数据库响应慢问题最多的就是查询了。现在大部分数据库都提供了性能分析的帮助手段。例如Oracle中会帮你直接找出慢的语句,并且提供优化方案。在MySQL中就要自己开启慢日志记录加以分析(记录可以保存在表或者文件中,默认是保存在文件中,我们系统使用的就是默认方式)。

先看看MySQL慢查询日志里面的记录长什么样的:

Time         Id Command  Argument
# Time: 141010 9:33:57
# User@Host: root[root] @ localhost [] Id:   1
# Query_time: 0.000342 Lock_time: 0.000142 Rows_sent: 3 Rows_examined: 3
use test;
SET timestamp=1412904837;
select * from t;

这个日志应该很好理解了,第一个#记录时间戳,第二个#记录执行命令的用户和地址信息,第三个#记录执行查询的时间、锁的时间、返回行数、被扫描的行数。接着后面记录真正执行的SQL语句。还可以通过以下命令看看cvs存储格式每个字段意义。

SHOW CREATE TABLE mysql.slow_log;

接下来说说如何获取和分析慢日志吧。

查看MySQL慢日志参数

进入启动好的MySQL,执行以下命令

mysql> show variables like '%slow_query%';

+---------------------------+----------------------------------------+
| Variable_name       | Value                 |
+---------------------------+----------------------------------------+
| slow_query_log      | OFF                  |
| slow_query_log_file    | /usr/local/mysql/data/cloudlu-slow.log |
+---------------------------+----------------------------------------+

这里告诉我们慢日志的日志存放位置,慢日志是否有开启。
那么什么样的查询需要被日志呢?在MySQL中, 没有index的查询 以及 超过指定时间同时超过指定扫描行数的查询 需要记录在慢日志查询里面。

那么它们的参数又是怎么查看的呢?

没有index的查询记录开关

mysql> show global variables like '%indexes%';

+----------------------------------------+-------+
| Variable_name             | Value |
+----------------------------------------+-------+
| log_queries_not_using_indexes     | OFF  |
| log_throttle_queries_not_using_indexes | 0   |
+----------------------------------------+-------+

第一个参数 表示是否开启记录没有index的查询,第二个

参数用来做日志记录的流量控制,一分钟可以记录多少条,默认0是表示不限制。

超过指定时长的查询开关

mysql> show global variables like '%long_query%';

+-----------------+-----------+
| Variable_name  | Value   |
+-----------------+-----------+
| long_query_time | 10.000000 |
+-----------------+-----------+
1 row in set (0.00 sec)

就一个参数指定超过多少时长的查询需要被记录

超过指定行数的扫描查询开关

mysql> show variables like '%min_examined_row_limit%';

+------------------------+-------+
| Variable_name     | Value |
+------------------------+-------+
| min_examined_row_limit | 0   |
+------------------------+-------+
1 row in set (0.00 sec)

默认是0,代表不现在扫描行数

设置开启MySQL慢日志参数

进入MySQL,输入以下命令或者在MySQL的启动配置文件里面修改或者给MySQL添加启动参数,进入MySQL后的修改如下:

set global long_query_time=0.1;
set global log_queries_not_using_indexes=on;
set global slow_query_log = on;

这里要斟酌的有2点,第一是超过什么时长的日志是有问题的,这个由系统需求来决定。第二是没有使用indexes的日志每分钟要记录多少条,要防止日志太多对性能产生影响。

在实际的日志分析中,通常慢日志的log数量不少,同时相同的查询被记录的条数也会很多,这里就需要如何从慢日志查询中找到最有问题,最需要优化的日志。在这方面,有很多分析工具,最基本的分析工具就是MySQL自带的mysqldumpslow,mysqldumpslow(Perl脚本)的输出示例:

[root@cloudlu bin]# ./mysqldumpslow -s t -t 1 /usr/local/mysql/data/cloudlu-slow.log 

 

Reading mysql slow query log from /usr/local/mysql/data/cloudlu-slow.log 
Count: 1 Time=0.00s (0s) Lock=0.00s (0s) Rows=3.0 (3), root[root]@localhost 
 select * from t 

一看就非常清楚,它的输出主要 统计不同慢sql的出现次数(Count 1),执行最长时间(Time 0.00s),累计总耗费时间(Time 0s),等待锁的时间(Lock 0.00s),等待锁的总时间(Lock 0s),发送给客户端的行总数(Rows 3.0),扫描的行总数(Rows 3),用户(root)以及sql语句本身。它最常用的参数包括:

  • -s 排序选项:c 查询次数 r 返回记录行数 t 查询时间
  • -t n:显示top n条查询

对于一般的分析已经差不多了,不过对于百分比等等数据mysqldumpslow就不够完善了。所以世界上多了很多各种MySQL慢日志分析工具,比较优秀的有mysqlsla(Perl脚本)和pt-query-digest(Perl脚本),可以提供Count, sql的执行次数及占总的slow log数量的百分比,Time, 执行时间, 包括总时间, 平均时间, 最小, 最大时间, 时间占到总慢sql时间的百分比,95% of Time, 去除最快和最慢的sql, 覆盖率占95%的sql的执行时间,Lock Time, 等待锁的时间,95% of Lock , 95%的慢sql等待锁时间,Rows sent, 结果行统计数量, 包括平均, 最小, 最大数量,Rows examined, 扫描的行数量,还可以生成表报,存储分析结果。这里就不一一介绍了。

通过这些慢日志分析软件定位到了慢查询语句就已经完成了SQL优化的一大半。接下来通过在MySQL中执行explain或者desc命令查看慢查询语句,可以看出为什么SQL查询慢。

mysql> explain select * from test.t \G 

*************************** 1. row *************************** 
      id: 1 
 select_type: SIMPLE 
    table: t 
     type: ALL 
possible_keys: NULL 
     key: NULL 
   key_len: NULL 
     ref: NULL 
     rows: 2 
    Extra: NULL 
1 row in set (0.00 sec) 

它的输出格式细节可以关注MySQL explain format,在输出中最要注意的是:
1. type:ALL是效率最差,最要注意的

2. key:是否有使用Key,key长度如何

3. Extra:最好不要出现filesort以及temporary,最主要是要关注在orderby和groupby。


Note: SQL优化是个很复杂的过程,有可能出现拆东墙补西墙的情况:比如给数据库表加入了索引之后,确实查询快了,可是存储空间加多了,插入删除操作耗时也增加了,如果在一个写多读少的系统中,执行这种优化可能会起到反效果。所以优化完之后千万不能大意,要持续监控系统,防止出现引入新瓶颈的情况。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AM

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL: Database Management System vs. Programming LanguageMySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AM

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL: Managing Data with SQL CommandsMySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AM

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

MySQL's Purpose: Storing and Managing Data EffectivelyMySQL's Purpose: Storing and Managing Data EffectivelyApr 16, 2025 am 12:16 AM

MySQL is an efficient relational database management system suitable for storing and managing data. Its advantages include high-performance queries, flexible transaction processing and rich data types. In practical applications, MySQL is often used in e-commerce platforms, social networks and content management systems, but attention should be paid to performance optimization, data security and scalability.

SQL and MySQL: Understanding the RelationshipSQL and MySQL: Understanding the RelationshipApr 16, 2025 am 12:14 AM

The relationship between SQL and MySQL is the relationship between standard languages ​​and specific implementations. 1.SQL is a standard language used to manage and operate relational databases, allowing data addition, deletion, modification and query. 2.MySQL is a specific database management system that uses SQL as its operating language and provides efficient data storage and management.

Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.