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
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.
MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.
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.
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.
In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.
The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.
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.
Abstract of the first paragraph of the article: When choosing software to develop Yi framework applications, multiple factors need to be considered. While native mobile application development tools such as XCode and Android Studio can provide strong control and flexibility, cross-platform frameworks such as React Native and Flutter are becoming increasingly popular with the benefits of being able to deploy to multiple platforms at once. For developers new to mobile development, low-code or no-code platforms such as AppSheet and Glide can quickly and easily build applications. Additionally, cloud service providers such as AWS Amplify and Firebase provide comprehensive tools