Table of Contents
Prepare the test data table and data
Analyze the reasons why excessive offset affects performance
Analysis of reasons affecting performance" >Analysis of reasons affecting performance
Speculation" >Speculation
Confirmed" >Confirmed
Home Database Mysql Tutorial Detailed explanation of the reasons and optimization methods for excessive offset affecting performance during mysql query

Detailed explanation of the reasons and optimization methods for excessive offset affecting performance during mysql query

Jun 08, 2018 pm 05:17 PM
mysql offset

mysql query uses the select command, combined with the limit and offset parameters to read records in the specified range. This article will introduce the reasons and optimization methods for excessive offset affecting performance during mysql queries.

Prepare the test data table and data

1. Create the table

CREATE TABLE `member` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(10) NOT NULL COMMENT '姓名', `gender` tinyint(3) unsigned NOT NULL COMMENT '性别', PRIMARY KEY (`id`), KEY `gender` (`gender`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy after login

2.Insert 1000000 records

<?php
$pdo = new PDO("mysql:host=localhost;dbname=user","root",&#39;&#39;);for($i=0; $i<1000000; $i++){    $name = substr(md5(time().mt_rand(000,999)),0,10);    $gender = mt_rand(1,2);    $sqlstr = "insert into member(name,gender) values(&#39;".$name."&#39;,&#39;".$gender."&#39;)";    $stmt = $pdo->prepare($sqlstr);    $stmt->execute();}
?>mysql> select count(*) from member;
+----------+| count(*) |
+----------+|  1000000 |
+----------+1 row in set (0.23 sec)
Copy after login


3. Current database version

mysql> select version();
+-----------+| version() |
+-----------+| 5.6.24    |
+-----------+1 row in set (0.01 sec)
Copy after login


Analyze the reasons why excessive offset affects performance

1. When the offset is small

mysql> select * from member where gender=1 limit 10,1;
+----+------------+--------+| id | name       | gender |
+----+------------+--------+| 26 | 509e279687 |      1 |
+----+------------+--------+1 row in set (0.00 sec)mysql> select * from member where gender=1 limit 100,1;
+-----+------------+--------+| id  | name       | gender |
+-----+------------+--------+| 211 | 07c4cbca3a |      1 |
+-----+------------+--------+1 row in set (0.00 sec)mysql> select * from member where gender=1 limit 1000,1;
+------+------------+--------+| id   | name       | gender |
+------+------------+--------+| 1975 | e95b8b6ca1 |      1 |
+------+------------+--------+1 row in set (0.00 sec)
Copy after login

When the offset is small, the query speed is very slow Fast and efficient.

2. When the offset is large

mysql> select * from member where gender=1 limit 100000,1;
+--------+------------+--------+| id     | name       | gender |
+--------+------------+--------+| 199798 | 540db8c5bc |      1 |
+--------+------------+--------+1 row in set (0.12 sec)mysql> select * from member where gender=1 limit 200000,1;
+--------+------------+--------+| id     | name       | gender |
+--------+------------+--------+| 399649 | 0b21fec4c6 |      1 |
+--------+------------+--------+1 row in set (0.23 sec)mysql> select * from member where gender=1 limit 300000,1;
+--------+------------+--------+| id     | name       | gender |
+--------+------------+--------+| 599465 | f48375bdb8 |      1 |
+--------+------------+--------+1 row in set (0.31 sec)
Copy after login

When the offset is large, efficiency problems will occur. As the offset increases, Execution efficiency decreases.

Analysis of reasons affecting performance

select * from member where gender=1 limit 300000,1;
Copy after login

Because the data table is InnoDB, according to the structure of the InnoDB index, The query process is:

  • Find the primary key value through the secondary index (find all ids with gender=1).

  • Then find the corresponding data block through the primary key index based on the found primary key value (find the corresponding data block content based on the id).

  • According to the value of offset, query the data of the primary key index 300001 times, and finally discard the previous 300000 entries and take out the last one.

But since the secondary index has found the primary key value, why do we need to use the primary key index to find the data block first, and then perform offset processing based on the offset value?

If after finding the primary key index, first perform offset offset processing, skip 300000 records, and then read the data block through the primary key index of the 300001th record, this can improve Efficiency.

If we only query the primary key, see what the difference is.

mysql> select id from member where gender=1 limit 300000,1;
+--------+| id     |
+--------+| 599465 |
+--------+1 row in set (0.09 sec)
Copy after login

Obviously, if we query only the primary key, the execution efficiency is greatly improved compared to querying all fields.

Speculation

Only querying the primary key
Because the secondary index has already found the primary key value, and the query only needs to read the primary key, so mysql will first perform the offset operation, and then read the data block based on the subsequent primary key index.

Need to query all fields
Because the secondary index only finds the primary key value, but the values ​​of other fields need to be read from the data block to obtain. Therefore, mysql will first read the data block content, then perform the offset operation, and finally discard the previous data that needs to be skipped and return the subsequent data.

Confirmed

There is a buffer pool in InnoDB, which stores recently accessed data pages, including data pages and index pages.

In order to test, restart mysql first, and then check the contents of the buffer pool.

mysql> select index_name,count(*) from information_schema.INNODB_BUFFER_PAGE where INDEX_NAME in(&#39;primary&#39;,&#39;gender&#39;) and TABLE_NAME like &#39;%member%&#39; group by index_name;
Empty set (0.04 sec)
Copy after login

You can see that after restarting, no data pages have been accessed.

Query all fields, and then check the contents of the buffer pool

mysql> select * from member where gender=1 limit 300000,1;
+--------+------------+--------+| id     | name       | gender |
+--------+------------+--------+| 599465 | f48375bdb8 |      1 |
+--------+------------+--------+1 row in set (0.38 sec)mysql> select index_name,count(*) from information_schema.INNODB_BUFFER_PAGE where INDEX_NAME in(&#39;primary&#39;,&#39;gender&#39;) and TABLE_NAME like &#39;%member%&#39; group by index_name;
+------------+----------+| index_name | count(*) |
+------------+----------+| gender     |      261 || PRIMARY    |     1385 |
+------------+----------+2 rows in set (0.06 sec)
Copy after login

It can be seen that there are ## in the member table in the buffer pool at this time #1385 data pages, 261 index pages.

Restart mysql to clear the buffer pool, and continue testing to query only the primary key

mysql> select id from member where gender=1 limit 300000,1;
+--------+| id     |
+--------+| 599465 |
+--------+1 row in set (0.08 sec)mysql> select index_name,count(*) from information_schema.INNODB_BUFFER_PAGE where INDEX_NAME in(&#39;primary&#39;,&#39;gender&#39;) and TABLE_NAME like &#39;%member%&#39; group by index_name;
+------------+----------+| index_name | count(*) |
+------------+----------+| gender     |      263 || PRIMARY    |       13 |
+------------+----------+2 rows in set (0.04 sec)
Copy after login

It can be seen that at this time, there are only # member tables in the buffer pool ##13

data pages, 263 index pages. Therefore, multiple I/O operations for accessing data blocks through the primary key index are reduced and execution efficiency is improved. Therefore, it can be confirmed that

The reason why excessive offset affects performance during mysql query is due to multiple I/O operations of accessing the data block through the primary key index.

(Note that only InnoDB has this problem, and the MYISAM index structure is different from InnoDB. The secondary indexes point directly to data blocks, so there is no such problem).

InnoDB and MyISAM engine index structure comparison chart

Detailed explanation of the reasons and optimization methods for excessive offset affecting performance during mysql query

##Optimization method

According to the above analysis, we know that querying all fields will cause I/O operations caused by multiple accesses to data blocks in the primary key index.

Therefore, we first find out the offset primary key, and then query all the contents of the data block based on the primary key index to optimize.

mysql> select a.* from member as a inner join (select id from member where gender=1 limit 300000,1) as b on a.id=b.id;
+--------+------------+--------+| id     | name       | gender |
+--------+------------+--------+| 599465 | f48375bdb8 |      1 |
+--------+------------+--------+1 row in set (0.08 sec)
Copy after login
This article explains the reasons and optimization methods for excessive offset affecting performance during mysql query. For more related content, please pay attention to the PHP Chinese website. related suggestion:

About the method of using regular PHP to remove width and height styles

Detailed explanation of file content deduplication and sorting

Interpretation of mysql case-sensitive configuration issues

The above is the detailed content of Detailed explanation of the reasons and optimization methods for excessive offset affecting performance during mysql query. 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's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

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.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

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.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

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.

See all articles