What is MySQL slow query? In fact, the query SQL statement takes a long time.
How long does it take to calculate a slow query? This actually varies from person to person. Some companies have a slow query threshold of 100ms, and some may have a threshold of 500ms. That is, if the query time exceeds this threshold, it is considered a slow query. Under normal circumstances, MySQL will not automatically enable slow query, and if it is enabled, the default threshold is 10 seconds
# slow_query_log 表示是否开启
mysql> show global variables like '%slow_query_log%';
+---------------------+--------------------------------------+
| Variable_name | Value |
+---------------------+--------------------------------------+
| slow_query_log | OFF |
| slow_query_log_file | /var/lib/mysql/0bd9099fc77f-slow.log |
+---------------------+--------------------------------------+
# long_query_time 表示慢查询的阈值,默认10秒
show global variables like '%long_query_time%';
+-----------------+-----------+
| Variable_name | Value |
+-----------------+-----------+
| long_query_time | 10.000000 |
+-----------------+-----------+
Copy after login
2. The dangers of slow query
Since we are so concerned about slow query, it must have some disadvantages. The common ones are as follows:
1. Poor user experience.
We have to wait for a long time to access something or save something, so why don’t we give up every minute? Wait, I know the experience will be poor, but setting the slow query threshold to 100ms seems too low. It should be acceptable for me to access something for 1-2 seconds. In fact, this threshold is not too low, because it is the threshold of a SQL, and you may have to check the SQL several times for one interface, and it is very common to even adjust the external interface.
2. Occupying MySQL memory and affecting performance
MySQL memory is inherently limited (large memory costs extra!). Why is SQL query slow? Sometimes it is because you scan the entire table and query a large amount of data, coupled with various filters, it becomes slow. Therefore, slow queries often mean an increase in memory usage. When the memory is high, the SQL queries that can be carried become smaller. Less, and performance deteriorates.
3. Causes DDL operation blocking
As we all know, the InnoDB engine adds row locks by default, but the locks are actually added to the index. If the filter conditions are not Creating an index will downgrade to table lock. Most of the reasons for slow queries are due to the lack of indexes. Therefore, if the slow query time is too long, the table lock time will also be very long. If DDL is executed at this time, it will cause blocking.
3. Common Scenarios of Slow Query
Since slow query causes so many problems, in what scenarios do slow queries generally occur?
1. No index added/failed to make good use of the index
In the case of
not adding an index, it will cause a full table scan; or The index is not reached (or the index is not the optimal index). These two situations will cause the number of scanned rows to increase, thereby slowing down the query time.
The following is an example of my test:
# 这是我的表结构,算是一种比较常规的表
create table t_user_article
(
id bigint unsigned auto_increment
primary key,
cid tinyint(2) default 0 not null comment 'id',
title varchar(100) not null,
author varchar(15) not null,
content text not null,
keywords varchar(255) not null,
description varchar(255) not null,
is_show tinyint(1) default 1 not null comment ' 1 0',
is_delete tinyint(1) default 0 not null comment ' 1 0',
is_top tinyint(1) default 0 not null comment ' 1 0',
is_original tinyint(1) default 1 not null,
click int(10) default 0 not null,
created_at timestamp default CURRENT_TIMESTAMP not null,
updated_at timestamp default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP
)
collate = utf8mb4_unicode_ci;
Copy after login
Under the above table structure, I passed
[Fill Database](https://filldb.info/) this The website randomly generated a batch of data for testing. It can be seen that without indexing, slow queries will begin after 50,000 pieces of data (assuming the threshold is 100ms)
-- 个人测试: 106000条数据,耗时约 90ms
select * from t_user_article t1, (select id from t_user_article where click > 0 order by id limit 100000, 10) t2 WHERE t1.id = t2.id;
Copy after login
第二种,分开查询,分开查询的意思就是分两次查,此时SQL变为:
-- 个人测试: 106000条数据,耗时约 80ms
select id from t_user_article where click > 0 order by id limit 100000, 10;
-- 个人测试: 106000条数据,耗时约 80ms
select * from t_user_article where id in (上述查询得到的ID)
select * from t_user_article where id in (select id from t_user_article where click > 0 limit 100000, 10)
Copy after login
但这时候执行你会发现抛出一个错误: “This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery’”,翻译过来就是子查询不支持Limit,解决办法也很简单,多嵌套一层即可:
-- 个人测试: 106000条数据,耗时约 200ms
select * from t_user_article where id in (select t.id from (select id from t_user_article where click > 0 order by id limit 100000, 10) as t)
Copy after login
但问题是测试后发现耗时反而变长了,所以并没有列举为一种解决办法。
4、使用FileSort查询
什么是FileSort查询呢?其实就是当你使用 order by 关键字时,如果待排序的内容不能由所使用的索引直接完成,MySQL就有可能会进行FileSort。
# click 字段此时未加索引
explain select id, click from t_user_article where click > 0 order by click limit 10;
# explain 结果:
type:ALL Extra:Using where; Using filesort
Copy after login
解决办法就是在 click 字段上加索引。
4.2 使用两个字段排序,但是排序规则不同,一个正序,一个倒序
# click 字段此时已加索引
explain select id, click from t_user_article where click > 0 order by click desc, id asc limit 10;
# explain 结果:
type:range Extra:Using where; Using index; Using filesort
The above is the detailed content of This article will give you a quick understanding of slow queries in MySQL. 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
MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.
You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".
MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.
Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.
MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.
MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen
MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.
Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus.
This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings