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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

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
......

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

/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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP's big data structure processing skills PHP's big data structure processing skills May 08, 2024 am 10:24 AM

Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the &quot;MySQL Native Password&quot; plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

The difference between oracle database and mysql The difference between oracle database and mysql May 10, 2024 am 01:54 AM

Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.

See all articles