Table of Contents
Question
Server layer and storage engine layer
那LIMIT是什么鬼?
怎么办?
吐个槽
Home Database Mysql Tutorial In-depth analysis of the LIMIT statement in MySQL

In-depth analysis of the LIMIT statement in MySQL

Oct 13, 2021 pm 07:02 PM
mysql

This article will take you to understand the LIMIT statement in MySQL and talk about a question - is MySQL's LIMIT so bad? I hope to be helpful!

In-depth analysis of the LIMIT statement in MySQL

Recently, many friends asked children about LIMIT in the Q&A group. Let me briefly describe this question.

Question

In order for the story to develop smoothly, we must first have a table:

CREATE TABLE t (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    key1 VARCHAR(100),
    common_field VARCHAR(100),
    PRIMARY KEY (id),
    KEY idx_key1 (key1)
) Engine=InnoDB CHARSET=utf8;
Copy after login

Table t contains 3 columns, and the id column is the primary key , the key1 column is a secondary index column. The table contains 10,000 records. [Related recommendations: mysql video tutorial]

When we execute the following statement, the secondary index idx_key1 is used:

mysql>  EXPLAIN SELECT * FROM t ORDER BY key1 LIMIT 1;
+----+-------------+-------+------------+-------+---------------+----------+---------+------+------+----------+-------+
| id | select_type | table | partitions | type  | possible_keys | key      | key_len | ref  | rows | filtered | Extra |
+----+-------------+-------+------------+-------+---------------+----------+---------+------+------+----------+-------+
|  1 | SIMPLE      | t     | NULL       | index | NULL          | idx_key1 | 303     | NULL |    1 |   100.00 | NULL  |
+----+-------------+-------+------------+-------+---------------+----------+---------+------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)
Copy after login

This is easy to understand, because In the secondary index idx_key1, the key1 column is ordered. The query is to retrieve the first record sorted by the key1 column. Then MySQL only needs to obtain the first secondary index record from idx_key1, and then directly return to the table to obtain the complete record.

But if we replace LIMIT 1 in the above statement with LIMIT 5000, 1, then we need to perform a full table scan and filesort. The execution plan is as follows:

mysql>  EXPLAIN SELECT * FROM t ORDER BY key1 LIMIT 5000, 1;
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra          |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------+
|  1 | SIMPLE      | t     | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 9966 |   100.00 | Using filesort |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------+
1 row in set, 1 warning (0.00 sec)
Copy after login

Some students don’t understand: LIMIT 5000, 1You can also use the secondary index idx_key1. We can scan the 5001st secondary index record first, and then scan the 5001st secondary index record first. Wouldn't it be nice to perform a table return operation on 5001 secondary index records? This cost is definitely better than a full table scan filesort.

I regret to tell you that due to the flaws in MySQL implementation, the above ideal situation will not occur. It will only perform a full table scan filesort stupidly. Let’s talk about what is going on. Son.

Server layer and storage engine layer

As we all know, MySQL is actually divided into server layer and storage engine layer:

  • The server layer is responsible for handling some common things, such as connection management, SQL syntax parsing, analysis of execution plans, etc.

  • The storage engine layer is responsible for specific data storage, such as Whether the data is stored in a file or in memory, what is the specific storage format, etc. We basically use the InnoDB storage engine now, and other storage engines are rarely used, so we will not cover other storage engines.

The execution of a SQL statement in MySQL obtains the final result through multiple interactions between the server layer and the storage engine layer. For example, the following query:

SELECT * FROM t WHERE key1 > &#39;a&#39; AND key1 < &#39;b&#39; AND common_field != &#39;a&#39;;
Copy after login

The server layer will analyze that the above statement can be executed using the following two options:

  • Option 1: Use full table scan

  • Option 2: Use the secondary index idx_key1. At this time, you need to scan all secondary index records with the key1 column value between ('a', 'b'), and each secondary index All records need to be returned to the table.

The server layer will analyze which of the above two options is lower cost, and then select the lower cost option as the execution plan. Then the interface provided by the storage engine is called to actually execute the query.

It is assumed here that option 2 is adopted, that is, the secondary index idx_key1 is used to execute the above query. Then the dialogue between the server layer and the storage engine layer can be as follows:

In-depth analysis of the LIMIT statement in MySQL

Server layer: "Hey, please check the ('a', ' of the idx_key1 secondary index b') The first record in the interval, and then return the complete record to me after returning to the table."

InnoDB: "Received, check it now", and then InnoDB uses the idx_key1 secondary index The corresponding B-tree quickly locates the first secondary index record in the scan interval ('a', 'b'), and then returns the table to get the complete clustered index record and returns it to the server layer.

In-depth analysis of the LIMIT statement in MySQL

After the server layer receives the complete clustered index record, it continues to determine whether the common_field!='a' condition is true. If it is not true, it will be discarded. record, otherwise the record is sent to the client. Then say to the storage engine: "Please give me the next record."

Tips:

The record sent to the client here is actually sent to the local network. Buffer, the buffer size is controlled by net_buffer_length, the default size is 16KB. Wait until the buffer is full before actually sending the network packet to the client.

InnoDB: "Received, check now". InnoDB finds the next secondary index record in the ('a', 'b') interval of idx_key1 based on the next_record attribute of the record, then performs a table return operation and returns the complete clustered index record to the server layer.

小贴士:

不论是聚簇索引记录还是二级索引记录,都包含一个称作next_record的属性,各个记录根据next_record连成了一个链表,并且链表中的记录是按照键值排序的(对于聚簇索引来说,键值指的是主键的值,对于二级索引记录来说,键值指的是二级索引列的值)。

In-depth analysis of the LIMIT statement in MySQL

server层收到完整的聚簇索引记录后,继续判断common_field!=&#39;a&#39;条件是否成立,如果不成立则舍弃该记录,否则将该记录发送到客户端。然后对存储引擎说:“请把下一条记录给我哈”

... 然后就不停的重复上述过程。

直到:

In-depth analysis of the LIMIT statement in MySQL

也就是直到InnoDB发现根据二级索引记录的next_record获取到的下一条二级索引记录不在('a', 'b')区间中,就跟server层说:“好了,('a', 'b')区间没有下一条记录了”

server层收到InnoDB说的没有下一条记录的消息,就结束查询。

现在大家就知道了server层和存储引擎层的基本交互过程了。

那LIMIT是什么鬼?

说出来大家可能有点儿惊讶,MySQL是在server层准备向客户端发送记录的时候才会去处理LIMIT子句中的内容。拿下边这个语句举例子:

SELECT * FROM t ORDER BY key1 LIMIT 5000, 1;
Copy after login

如果使用idx_key1执行上述查询,那么MySQL会这样处理:

  • server层向InnoDB要第1条记录,InnoDB从idx_key1中获取到第一条二级索引记录,然后进行回表操作得到完整的聚簇索引记录,然后返回给server层。server层准备将其发送给客户端,此时发现还有个LIMIT 5000, 1的要求,意味着符合条件的记录中的第5001条才可以真正发送给客户端,所以在这里先做个统计,我们假设server层维护了一个称作limit_count的变量用于统计已经跳过了多少条记录,此时就应该将limit_count设置为1。

  • server层再向InnoDB要下一条记录,InnoDB再根据二级索引记录的next_record属性找到下一条二级索引记录,再次进行回表得到完整的聚簇索引记录返回给server层。server层在将其发送给客户端的时候发现limit_count才是1,所以就放弃发送到客户端的操作,将limit_count加1,此时limit_count变为了2。

  • ... 重复上述操作

  • 直到limit_count等于5000的时候,server层才会真正的将InnoDB返回的完整聚簇索引记录发送给客户端。

从上述过程中我们可以看到,由于MySQL中是在实际向客户端发送记录前才会去判断LIMIT子句是否符合要求,所以如果使用二级索引执行上述查询的话,意味着要进行5001次回表操作。server层在进行执行计划分析的时候会觉得执行这么多次回表的成本太大了,还不如直接全表扫描+filesort快呢,所以就选择了后者执行查询。

怎么办?

由于MySQL实现LIMIT子句的局限性,在处理诸如LIMIT 5000, 1这样的语句时就无法通过使用二级索引来加快查询速度了么?其实也不是,只要把上述语句改写成:

SELECT * FROM t, (SELECT id FROM t ORDER BY key1 LIMIT 5000, 1) AS d
    WHERE t.id = d.id;
Copy after login

这样,SELECT id FROM t ORDER BY key1 LIMIT 5000, 1作为一个子查询单独存在,由于该子查询的查询列表只有一个id列,MySQL可以通过仅扫描二级索引idx_key1执行该子查询,然后再根据子查询中获得到的主键值去表t中进行查找。

这样就省去了前5000条记录的回表操作,从而大大提升了查询效率!

吐个槽

设计MySQL的大叔啥时候能改改LIMIT子句的这种超笨的实现呢?还得用户手动想欺骗优化器的方案才能提升查询效率~

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of In-depth analysis of the LIMIT statement 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

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)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

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.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

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: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

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.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

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.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

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 Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

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: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

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.

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

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

See all articles