Home Database Mysql Tutorial linux下开启mysql慢查询,分析查询语句

linux下开启mysql慢查询,分析查询语句

Jun 07, 2016 pm 03:12 PM
linux mysql Why analyze turn on Inquire statement

一,为什么要开启这个查询呢? 数据库是很容易产生瓶颈的地方,现在Nosql大家讨论这么热,估计都被数据库搞郁闷了。mysql中最影响速度的就是那些查询非常慢的语句,这些慢的语句,可能是写的不够合理或者是大数据下多表的联合查询等等,所以我们要找出这些语

一,为什么要开启这个查询呢?

数据库是很容易产生瓶颈的地方,现在Nosql大家讨论这么热,估计都被数据库搞郁闷了。mysql中最影响速度的就是那些查询非常慢的语句,这些慢的语句,可能是写的不够合理或者是大数据下多表的联合查询等等,所以我们要找出这些语句,分析原因,加以优化。这也是发这篇博文的原因

二,开启mysql的慢查询

方法1,用命令开启慢查询

查看复制打印?

  1. mysql> show variables like "%long%";         //查看一下默认为慢查询的时间10秒  
  2. +-----------------+-----------+  
  3. | Variable_name   | Value     |  
  4. +-----------------+-----------+  
  5. | long_query_time | 10.000000 |  
  6. +-----------------+-----------+  
  7. 1 row in set (0.00 sec)  
  8.   
  9. mysql> set global long_query_time=2;          //设置成2秒,加上global,下次进mysql已然生效  
  10. Query OK, 0 rows affected (0.00 sec)  
  11.   
  12. mysql> show variables like "%slow%";          //查看一下慢查询是不是已经开启  
  13. +---------------------+---------------------------------+  
  14. | Variable_name       | Value                           |  
  15. +---------------------+---------------------------------+  
  16. | log_slow_queries    | OFF                             |  
  17. | slow_launch_time    | 2                               |  
  18. | slow_query_log      | OFF                             |  
  19. | slow_query_log_file | /usr/local/mysql/mysql-slow.log |  
  20. +---------------------+---------------------------------+  
  21. 4 rows in set (0.00 sec)  
  22.   
  23. mysql> set slow_query_log='ON';                        //加上global,不然会报错的。  
  24. ERROR 1229 (HY000): Variable 'slow_query_log' is a GLOBAL variable and should be set with SET GLOBAL  
  25. mysql> set global slow_query_log='ON';            //启用慢查询  
  26. Query OK, 0 rows affected (0.28 sec)  
  27.   
  28. mysql> show variables like "%slow%";              //查看是否已经开启  
  29. +---------------------+---------------------------------+  
  30. | Variable_name       | Value                           |  
  31. +---------------------+---------------------------------+  
  32. | log_slow_queries    | ON                              |  
  33. | slow_launch_time    | 2                               |  
  34. | slow_query_log      | ON                              |  
  35. | slow_query_log_file | /usr/local/mysql/mysql-slow.log |  
  36. +---------------------+---------------------------------+  
  37. 4 rows in set (0.00 sec)  

方法2,修改mysql的配置文件my.cnf

在[mysqld]里面加上以下内容

  1. long_query_time = 2  
  2. log-slow-queries = /usr/local/mysql/mysql-slow.log  

重起一下
/usr/local/mysql/libexec/mysqld restart

三,分析工具

分析工具干什么事的呢,其实就是把mysql-slow.log里面记录下来的数据,分析一下显示出来。其实自己写一个shell脚本也是可以把要的信息取出来的。我们来看一下mysql-slow.log里面到底是什么东西

查看复制打印?

  1. [root@BlackGhost mysql]# cat mysql-slow.log     //查看命令  
  2. /usr/local/mysql/libexec/mysqld, Version: 5.1.26-rc-log (Source distribution). started with:  
  3. Tcp port: 3306  Unix socket: /tmp/mysql.sock  
  4. Time                 Id Command    Argument  
  5. # Time: 100814 13:28:30  
  6. # User@Host: root[root] @ localhost []  
  7. # Query_time: 10.096500  Lock_time: 0.045791 Rows_sent: 1  Rows_examined: 2374192  
  8. SET timestamp=1281763710;  
  9. 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);  
  10. # Time: 100814 13:37:02  
  11. # User@Host: root[root] @ localhost []  
  12. # Query_time: 10.394134  Lock_time: 0.000091 Rows_sent: 1  Rows_examined: 2374192  
  13. SET timestamp=1281764222;  
  14. 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);  
  15. # Time: 100814 13:37:16  
  16. # User@Host: root[root] @ localhost []  
  17. # Query_time: 4.608920  Lock_time: 0.000078 Rows_sent: 1  Rows_examined: 1260544  
  18. SET timestamp=1281764236;  
  19. 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;  

看到了,就是记录一下sql语句的执行情况,包括执行时间,锁定时间等,所以要不要分析工具看个人情况,分析工具很多,在这儿只说一下mysql自带的慢查询分析工具mysqldumpslow的使用方法。

查看复制打印?

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

例子:

[root@BlackGhost bin]# ./mysqldumpslow -s r -t 20 /usr/local/mysql/mysql-slow.log

[root@BlackGhost bin]# ./mysqldumpslow -s r -t 20 -g 'count' /usr/local/mysql/mysql-slow.log


-----整理自网上

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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
How to understand DMA operations in C? How to understand DMA operations in C? Apr 28, 2025 pm 10:09 PM

DMA in C refers to DirectMemoryAccess, a direct memory access technology, allowing hardware devices to directly transmit data to memory without CPU intervention. 1) DMA operation is highly dependent on hardware devices and drivers, and the implementation method varies from system to system. 2) Direct access to memory may bring security risks, and the correctness and security of the code must be ensured. 3) DMA can improve performance, but improper use may lead to degradation of system performance. Through practice and learning, we can master the skills of using DMA and maximize its effectiveness in scenarios such as high-speed data transmission and real-time signal processing.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

How to handle high DPI display in C? How to handle high DPI display in C? Apr 28, 2025 pm 09:57 PM

Handling high DPI display in C can be achieved through the following steps: 1) Understand DPI and scaling, use the operating system API to obtain DPI information and adjust the graphics output; 2) Handle cross-platform compatibility, use cross-platform graphics libraries such as SDL or Qt; 3) Perform performance optimization, improve performance through cache, hardware acceleration, and dynamic adjustment of the details level; 4) Solve common problems, such as blurred text and interface elements are too small, and solve by correctly applying DPI scaling.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

What is the difference between php framework laravel and yii What is the difference between php framework laravel and yii Apr 30, 2025 pm 02:24 PM

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

How to configure the character set and collation rules of MySQL How to configure the character set and collation rules of MySQL Apr 29, 2025 pm 04:06 PM

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

See all articles