Home Database Mysql Tutorial Code summary of Mysql slow query operation

Code summary of Mysql slow query operation

Mar 24, 2017 pm 01:36 PM
mysql slow query

The following editor will bring you a summary of MysqlSlowQuery operations. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor to take a look

Mysql slow query explanation

MySQL’s slow query log is a type provided by MySQL Logging, which is used to record statements whose response time exceeds the threshold in MySQL, specifically refers to SQL whose running time exceeds the long_query_time value, which will be recorded in the slow query log. The default value of long_query_time is 10, which means running statements for more than 10S. By default, Mysql database does not start the slow query log. We need to manually set this parameter. Of course, if it is not needed for tuning, it is generally not recommended to start this parameter, because turning on the slow query log will cause or More or less will have a certain performance impact. The slow query log supports writing log records to files and also supports writing log records to database tables; the slow query log is used to record some query statements that are too slow, which can help administrators analyze the problem. The log defaults to no To enable it, you need to add a series of parameters to the configuration file to start it manually

Reason for turning on Mysql slow query

The database is a place where bottlenecks can easily occur. Nowadays, Nosql is being discussed so much that everyone is probably depressed by the database. What most affects the speed of MySQL are those very slow query statements. These slow statements may be written unreasonably or are joint queries of multiple tables under big data, etc., so we need to find out these statement, analyze the reasons, and optimize them. This is also the reason for posting this blog post

Enable mysql slow query method

1) Method 1 , Log in to the mysql database terminal and open

mysql> show variables like "%long%";    
<SPAN style="COLOR: #ff00ff"> //查看一下默认为慢查询的时间10秒 </SPAN> 
+-----------------+-----------+  
| Variable_name  | Value   |  
+-----------------+-----------+  
| long_query_time | 10.000000 |  
+-----------------+-----------+  
1 row in set (0.00 sec)  
  
mysql> set global long_query_time=1;     
<SPAN style="COLOR: #ff00ff">//设置成1秒,加上global,下次进mysql已然生效</SPAN>  
Query OK, 0 rows affected (0.00 sec)  
 
mysql> show variables like "%slow%";     
<SPAN style="COLOR: #ff00ff"> //查看一下慢查询是不是已经开启 </SPAN> 
+---------------------+---------------------------------+  
| Variable_name    | Value              |  
+---------------------+---------------------------------+  
| log_slow_queries  | OFF               |  
| slow_launch_time  | 2                |  
| slow_query_log   | OFF               |  
| slow_query_log_file | /usr/local/mysql/mysql-slow.log |  
+---------------------+---------------------------------+  
4 rows in set (0.00 sec)  
  
mysql> set slow_query_log=&#39;ON&#39;;          
<SPAN style="COLOR: #ff00ff"> //加上global,不然会报错的</SPAN> 
ERROR 1229 (HY000): Variable &#39;slow_query_log&#39; is a GLOBAL variable and should be set with SET GLOBAL 
mysql> set global slow_query_log=&#39;ON&#39;;      
<SPAN style="COLOR: #ff00ff">//这个参数设置为ON,表示启用慢查询,可以捕获执行时间超过一定数值的SQL语句。</SPAN> 
Query OK, 0 rows affected (0.28 sec)  
  
mysql> show variables like "%slow%";       
<SPAN style="COLOR: #ff00ff">//查看是否已经开启 </SPAN> 
+---------------------+---------------------------------+  
| Variable_name    | Value              |  
+---------------------+---------------------------------+  
| log_slow_queries  | ON               |  
| slow_launch_time  | 2                |  
| slow_query_log   | ON               |  
| slow_query_log_file | /usr/local/mysql/mysql-slow.log |  
+---------------------+---------------------------------+  
4 rows in set (0.00 sec)
Copy after login

Method 2. Modify the mysql configuration file my.cnf

[root@www ~]# vim /etc/mysql.cnf
Add the following content in the [mysqld] area configuration
......

slow_query_log = 1
      
//开启慢查询日志,将1改为ON也可以
long_query_time = 1
      
//mysql慢查询时间,指定达到多少秒才算慢查询;这里推荐设置超过1秒的执行语句就会被记录到慢查询日志中
slow_query_log_file= /var/lib/mysql/mysql-slow.log
     
//慢查询日志路径。这里slow_query_log_file修改为log-slow-queries 也可以
//主要是上面三行内容,还可以添加下面几行细节性配置
long-queries-not-using-indexes
     
//记录没有使用索引的查询语句
min_examined_row_limit = 1000
    
 //记录查找了多达1000次而引起的慢查询
log-slow-admin-statements
     
  //记录ALTER TABLE等语句引发的慢查询
log-slow-slave-statements       
 //记录从服务器产生的慢查询
Copy after login


Analysis Tool

The analysis tool is actually to analyze the data recorded in mysql-slow.log. It will be displayed at once (in fact, you can also get the required information out by writing a shell script yourself).

# [root@www ~]#Cat mysql-slow.log // View command


The execution status, including execution time, locking time, etc., so whether you want an analysis tool depends on your personal situation. There are many analysis tools. Here I will only talk about how to use the slow query analysis tool mysqldumpslow that comes with mysql.

[root@www ~]# mysqldumpslow -h

/usr/local/mysql/libexec/mysqld, Version: 5.1.26-rc-log (Source distribution). started with:  
Tcp port: 3306 Unix socket: /tmp/mysql.sock  
Time         Id Command  Argument  
# Time: 100814 13:28:30  
# User@Host: root[root] @ localhost []  
# Query_time: 10.096500 Lock_time: 0.045791 Rows_sent: 1 Rows_examined: 2374192  
SET timestamp=1281763710;  
select count(distinct ad_code) as x from ad_visit_history where ad_code in (select ad_code from ad_list where media_id=15);  
# Time: 100814 13:37:02  
# User@Host: root[root] @ localhost []  
# Query_time: 10.394134 Lock_time: 0.000091 Rows_sent: 1 Rows_examined: 2374192  
SET timestamp=1281764222;  
select count(distinct ad_code) as x from ad_visit_history where ad_code in (select ad_code from ad_list where media_id=15);  
# Time: 100814 13:37:16  
# User@Host: root[root] @ localhost []  
# Query_time: 4.608920 Lock_time: 0.000078 Rows_sent: 1 Rows_examined: 1260544  
SET timestamp=1281764236;  
select count(*) as cou from ad_visit_history where ad_code in (select ad_code from ad_list where id=41) order by id desc;
Copy after login

Example:

Option h requires an argument  
ERROR: bad option 
  
Usage: mysqldumpslow [ OPTS... ] [ LOGS... ]  
  
Parse and summarize the MySQL slow query log. Options are  
  
 --verbose  verbose  
 --debug   debug  
 --help    write this text to standard output  
  
 -v      verbose  
 -d      debug     //查错  
 -s ORDER   what to sort by (t, at, l, al, r, ar etc), &#39;at&#39; is default   //排序方式query次数,时间,lock的时间和返回的记录数来排序  
 -r      reverse the sort order (largest last instead of first)    //倒排序  
 -t NUM    just show the top n queries                    //显示前N多个  
 -a      don&#39;t abstract all numbers to N and strings to &#39;S&#39; 
 -n NUM    abstract numbers with at least n digits within names  //抽象的数字,至 少有n位内的名称 
 -g PATTERN  grep: only consider stmts that include this string   //配置模式 
 -h HOSTNAME hostname of db server for *-slow.log filename (can be wildcard),   //mysql所以机器名或者IP 
 default is &#39;*&#39;, i.e. match all 
 -i NAME   name of server instance (if using mysql.server startup script) 
 -l      don&#39;t subtract lock time from total time      //总时间中不减去锁定时间
Copy after login

The above is the detailed content of Code summary of Mysql slow query operation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

See all articles