Slowlog中小于long_query_time时间设置的query

本文深入解析MySQL慢查询参数log_queries_not_using_indexes的作用与使用方法,包括其在不同版本中的表现和配置建议,以及如何利用此参数优化数据库性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mysql Version :5.1.72

OS Version :CentOS release 6.4 (Final)


说到慢查询,有点老生常谈了,但是慢查询相关的有个参数可能会被很多人忽略。


log_queries_not_using_indexes

              这个参数设置当查询没有使用索引的情况下,是否记录到slowlog中。



模拟情景:






当前long_query_time = 1 && log_queries_not_using_indexes = on


运行一个全表扫描的sql:



当执行当前sql的时候,查看slowlog会发现,虽然long_query_time=1,但是这条sql仍然会被记录在slowlog中


图中看到query_time:0.001311秒



如果你使用的mysql版本大于5.6.5,也可以通过设置


log_throttle_queries_not_using_indexes

                 这个参数表示每分钟允许记录到slowlog且未使用索引的次数。默认值为0,标识没有限制。



相关文档(摘取Mysql 5.1官方文档):

5.2.5 The Slow Query Log

The slow query log consists of SQL statements that took more than long_query_time seconds to execute and (as of MySQL 5.1.21) required at least min_examined_row_limit rows to be examined. The default value oflong_query_time is 10. Beginning with MySQL 5.1.21, the minimum is 0, and the value can be specified to a resolution of microseconds. For logging to a file, times are written including the microseconds part. For logging to tables, only integer times are written; the microseconds part is ignored. Prior to MySQL 5.1.21, the minimum value is 1, and the value for this variable must be an integer.

By default, administrative statements are not logged, nor are queries that do not use indexes for lookups. This behavior can be changed using --log-slow-admin-statements and --log-queries-not-using-indexes, as described later.

The time to acquire the initial locks is not counted as execution time. mysqld writes a statement to the slow query log after it has been executed and after all locks have been released, so log order might differ from execution order.

Control the slow query log at server startup as follows:

If the slow query log file is enabled but no name is specified, the default name is host_name-slow.log and the server creates the file in the same directory where it creates the PID file. If a name is given, the server creates the file in the data directory unless an absolute path name is given to specify a different directory.

To disable or enable the slow query log or change the log file name at runtime, use the global slow_query_logand slow_query_log_file system variables. Set slow_query_log to 0 (or OFF) to disable the log or to 1 (or ON) to enable it. Set slow_query_log_file to specify the name of the log file. If a log file already is open, it is closed and the new file is opened.

When the slow query log is enabled, the server writes output to any destinations specified by the --log-outputoption or log_output system variable. If you enable the log, the server opens the log file and writes startup messages to it. However, further logging of queries to the file does not occur unless the FILE log destination is selected. If the destination is NONE, the server writes no queries even if the slow query log is enabled. Setting the log file name has no effect on logging if the log destination value does not contain FILE.

The server writes less information to the slow query log (and binary log) if you use the --log-short-formatoption.

To include slow administrative statements in the statements written to the slow query log, use the --log-slow-admin-statements server option. Administrative statements include ALTER TABLEANALYZE TABLECHECK TABLECREATE INDEXDROP INDEXOPTIMIZE TABLE, and REPAIR TABLE.

To include queries that do not use indexes for row lookups in the statements written to the slow query log, use the --log-queries-not-using-indexes server option. See Section 5.1.3, “Server Command Options”. When such queries are logged, the slow query log may grow quickly.

The server uses the controlling parameters in the following order to determine whether to write a query to the slow query log:

  1. The query must either not be an administrative statement, or --log-slow-admin-statements must have been specified.

  2. The query must have taken at least long_query_time seconds, or --log-queries-not-using-indexes must have been specified and the query used no indexes for row lookups.

  3. The query must have examined at least min_examined_row_limit rows.

The server does not write queries handled by the query cache to the slow query log, nor queries that would not benefit from the presence of an index because the table has zero rows or one row.

Prior to MySQL 5.1.45, replication slaves did not write replicated queries to the slow query log, even if the same queries were written to the slow query log on the master. (Bug #23300) In MySQL 5.1.45 and later, this behavior can be overridden using the --log-slow-slave-statements option.

The slow query log should be protected because logged statements might contain passwords. See Section 6.1.2.3, “Passwords and Logging”.

The slow query log can be used to find queries that take a long time to execute and are therefore candidates for optimization. However, examining a long slow query log can become a difficult task. To make this easier, you can process a slow query log file using the mysqldumpslow command to summarize the queries that appear in the log. See Section 4.6.8, “mysqldumpslow — Summarize Slow Query Log Files”.





<think>我们正在处理用户关于MySQL8查询慢SQL的方法的问题。根据引用内容,我们可以总结出以下步骤:1.开启慢查询日志:这是记录慢SQL的基础。2.设置慢查询的阈值(long_query_time):定义超过多少秒的查询为慢查询。3.查看慢查询日志:可以通过工具如mysqldumpslow来查看。4.使用EXPLAIN分析慢查询:分析SQL的执行计划。在MySQL8中,这些基本步骤仍然适用,但可能有新的特性或命令变化。因此,我们需要按照以下步骤详细说明:###步骤1:开启慢查询日志在MySQL8中,可以通过设置参数`slow_query_log`来开启慢查询日志。有两种方法:动态设置(无需重启)和修改配置文件(需重启)。动态设置:```sql--开启慢查询日志SETGLOBALslow_query_log='ON';```###步骤2:设置慢查询阈值设置`long_query_time`,单位为秒。例如,设置阈值为2秒:```sqlSETGLOBALlong_query_time=2;```注意:这个设置可能只对新会话生效,有时需要重新连接才能生效。###步骤3:指定慢查询日志文件路径(可选)如果需要,可以设置日志文件路径:```sqlSETGLOBALslow_query_log_file='/path/to/your/log/file.log';```###步骤4:记录未使用索引的查询(可选)还可以设置记录未使用索引的查询(即使它们没有超过阈值):```sqlSETGLOBALlog_queries_not_using_indexes='ON';```###步骤5:修改配置文件(永久生效)若要永久生效,需修改MySQL配置文件(如my.cnf或my.ini):```ini[mysqld]slow_query_log=ONlong_query_time=2slow_query_log_file=/var/log/mysql/slow.loglog_queries_not_using_indexes=ON```修改后重启MySQL服务。###步骤6:查看慢查询日志可以使用`mysqldumpslow`工具(MySQL自带)来查看慢查询日志。例如:```bashmysqldumpslow-st-t10/var/log/mysql/slow.log```该命令将显示最慢的10个查询(按总时间排序)。###步骤7:使用性能模式(PerformanceSchema)和系统视图MySQL8还提供了性能模式(PerformanceSchema)和`sys`库来监控性能。例如:```sql--使用sys库查看慢查询SELECT*FROMsys.statement_analysisWHEREquery_time>2;```###步骤8:使用EXPLAIN分析慢查询对于从慢查询日志中发现的SQL,使用`EXPLAIN`或`EXPLAINFORMAT=JSON`来查看执行计划:```sqlEXPLAINSELECT*FROMyour_tableWHERE...;```###注意事项-确保有足够的磁盘空间存放慢查询日志。-在生产环境中,开启慢查询日志可能会对性能有轻微影响,但通常可以接受。-定期分析慢查询日志以优化数据库。###引用说明根据用户提供的引用,我们参考了以下内容:-引用[1]:开启慢查询日志并设置阈值[^1]。-引用[2]:使用`mysqldumpslow`工具和`EXPLAIN`分析[^2]。-引用[3]:监控慢查询的数量[^3]。-引用[4]:提到了MyBatis一级缓存,但此内容与直接查询MySQL慢SQL关系不大,故未采用[^4]。因此,以上步骤综合了引用内容并结合MySQL8的实践。§§相关问题§§1.如何优化MySQL8中的慢查询?2.除了慢查询日志,MySQL8还有哪些监控性能的方法?3.如何自动监控和报告MySQL中的慢查询?</think>### MySQL 8 查询慢 SQL 的方法 在 MySQL 8 中查询慢 SQL 主要通过以下步骤实现,核心是**开启慢查询日志**并**分析日志记录**: #### 1. **开启慢查询日志** ```sql -- 动态开启(无需重启) SET GLOBAL slow_query_log = 'ON'; -- 设置慢查询阈值(单位:秒) SET GLOBAL long_query_time = 2; -- 超过2秒的查询视为慢SQL -- 指定日志文件路径(可选) SET GLOBAL slow_query_log_file = '/var/log/mysql/slow.log'; ``` > 📌 注意:`long_query_time` 默认值为 10 秒,建议根据业务调整[^1]。 #### 2. **永久配置(修改 my.cnf)** ```ini [mysqld] slow_query_log = ON long_query_time = 1 # 阈值设为1秒 slow_query_log_file = /var/log/mysql/slow.log log_queries_not_using_indexes = ON # 记录未使用索引的查询(可选) ``` 修改后需重启 MySQL 服务生效[^2]。 #### 3. **查看慢查询日志** - **直接查看日志文件**: ```bash tail -f /var/log/mysql/slow.log ``` - **使用 `mysqldumpslow` 工具分析**: ```bash # 按总耗时排序,显示前10条慢SQL mysqldumpslow -s t -t 10 /var/log/mysql/slow.log # 解析特定类型的查询(如SELECT) mysqldumpslow -s t -t 10 -g 'SELECT' /var/log/mysql/slow.log ``` #### 4. **使用 Performance Schema 监控** MySQL 8 强化了性能监控: ```sql -- 查看当前慢SQL统计 SELECT * FROM performance_schema.events_statements_summary_by_digest WHERE SUM_TIMER_WAIT > 1e12; -- 筛选执行时间>1秒的SQL -- 实时监控执行计划 EXPLAIN FORMAT=JSON SELECT * FROM orders WHERE amount > 1000; ``` #### 5. **优化慢SQL的步骤** 1. 从日志中定位高耗时 SQL 2. 使用 `EXPLAIN` 分析执行计划: ```sql EXPLAIN SELECT * FROM users WHERE last_login < NOW() - INTERVAL 30 DAY; ``` 3. 关注关键指标: - `type` 列:避免 `ALL`(全表扫描) - `rows` 列:扫描行数越少越好 - `Extra` 列:警惕 `Using filesort`/`Using temporary` > ⚠️ 注意事项: > - 生产环境开启慢查询日志对性能影响通常小于 1%[^3] > - 日志文件需定期归档(如用 `logrotate`) > - 结合监控工具如 Prometheus + Grafana 实现实时告警 --- ### 示例分析结果 慢查询日志条目示例: ```log # Time: 2023-10-05T08:42:31.123456Z # Query_time: 3.141592 Lock_time: 0.001000 Rows_sent: 0 Rows_examined: 1000000 SET timestamp=1696495351; SELECT * FROM order_details WHERE product_id IN (SELECT id FROM products WHERE stock=0); ``` 通过 `EXPLAIN` 发现子查询导致全表扫描,优化为 JOIN 后耗时降至 0.05 秒。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值