search
HomeDatabaseMysql TutorialMySQL Paging Performance Optimization Guide

Many applications tend to only display the latest or most popular records, but in order for old records to still be accessible, a paging navigation bar is needed. However, how to better implement paging through MySQL has always been a headache. While there is no off-the-shelf solution, understanding the underlying layers of a database can help to optimize paginated queries.

Let’s take a look at a commonly used query with poor performance.

SELECT *
FROM city
ORDER BY id DESC
LIMIT 0, 15

This query takes 0.00sec. So, what's wrong with this query? In fact, there is no problem with this query statement and parameters, because it uses the primary key of the table below and only reads 15 records.

CREATE TABLE city (
  id int(10) unsigned NOT NULL AUTO_INCREMENT,
  city varchar(128) NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB;

The real problem is when the offset (paging offset) is very large, like the following:

SELECT *
FROM city
ORDER BY id DESC
LIMIT 100000, 15;

The above query takes 0.22sec when there are 2M rows of records, view it through EXPLAIN The SQL execution plan can find that the SQL retrieved 100015 rows, but only 15 rows were needed in the end. Large paging offsets increase the data used, and MySQL loads a lot of data into memory that will ultimately not be used. Even if we assume that most website users only access the first few pages of data, a small number of requests with large page offsets can cause harm to the entire system. Facebook is aware of this, but instead of optimizing the database in order to handle more requests per second, Facebook focuses on reducing the variance of request response times.

For paging requests, there is another piece of information that is also very important, which is the total number of records. We can easily get the total number of records through the following query.

SELECT COUNT(*)
FROM city;

However, the above SQL takes 9.28sec when using InnoDB as the storage engine. An incorrect optimization is to use SQL_CALC_FOUND_ROWS. SQL_CALC_FOUND_ROWS can prepare the number of records that meet the conditions in advance during paging query, and then just execute a select FOUND_ROWS(); to get the total number of records. But in most cases, shorter query statements do not mean improved performance. Unfortunately, this paging query method is used in many mainstream frameworks. Let's take a look at the query performance of this statement.

SELECT SQL_CALC_FOUND_ROWS *
FROM city
ORDER BY id DESC
LIMIT 100000, 15;

This statement takes 20.02sec, twice as long as the previous one. It turns out that using SQL_CALC_FOUND_ROWS for paging is a very bad idea.

Let’s take a look at how to optimize. The article is divided into two parts. The first part is how to get the total number of records, and the second part is to get the real records.

Efficiently calculate the number of rows

If the engine used is MyISAM, you can directly execute COUNT(*) to get the number of rows. Similarly, in a heap table, the row number is also stored in the table's metainformation. But if the engine is InnoDB, the situation will be more complicated, because InnoDB does not save the specific number of rows in the table.
We can cache the number of rows, and then update it regularly through a daemon process or when some user operations cause the cache to become invalid, execute the following statement:

SELECT COUNT(*)
FROM city
USE INDEX(PRIMARY);

Get the record

Now enter the most important part of this article and obtain the records to be displayed in pagination. As mentioned above, large offsets will affect performance, so we need to rewrite the query statement. For demonstration, we create a new table "news", sort it by topicality (the latest release is at the top), and implement a high-performance paging. For simplicity, we assume that the ID of the latest news release is also the largest.

CREATE TABLE news(
   id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
   title VARCHAR(128) NOT NULL
) ENGINE=InnoDB;

A more efficient way is based on the last news ID displayed by the user. The statement to query the next page is as follows. You need to pass in the last ID displayed on the current page.

SELECT *
FROM news WHERE id < $last_id
ORDER BY id DESC
LIMIT $perpage

The statement for querying the previous page is similar, except that the first ID of the current page needs to be passed in, and in reverse order.

SELECT *
FROM news WHERE id > $last_id
ORDER BY id ASC
LIMIT $perpage

The above query method is suitable for simple paging, that is, no specific page navigation is displayed, only "previous page" and "next page" are displayed. For example, the footer of a blog displays "previous page" ”, “Next page” button. But if it is still difficult to achieve real page navigation, let’s look at another way.

SELECT id
FROM (
   SELECT id, ((@cnt:= @cnt + 1) + $perpage - 1) % $perpage cnt
   FROM news 
   JOIN (SELECT @cnt:= 0)T
   WHERE id < $last_id
   ORDER BY id DESC
   LIMIT $perpage * $buttons
)C
WHERE cnt = 0;

通过上面的语句可以为每一个分页的按钮计算出一个offset对应的id。这种方法还有一个好处。假设,网站上正在发布一片新的文章,那么所有文章的位置都会往后移一位,所以如果用户在发布文章时换页,那么他会看见一篇文章两次。如果固定了每个按钮的offset Id,这个问题就迎刃而解了。Mark Callaghan发表过一篇类似的博客,利用了组合索引和两个位置变量,但是基本思想是一致的。

如果表中的记录很少被删除、修改,还可以将记录对应的页码存储到表中,并在该列上创建合适的索引。采用这种方式,当新增一个记录的时候,需要执行下面的查询重新生成对应的页号。

SET p:= 0;
UPDATE news SET page=CEIL((p:= p + 1) / $perpage) ORDER BY id DESC;

当然,也可以新增一个专用于分页的表,可以用个后台程序来维护。

UPDATE pagination T
JOIN (
   SELECT id, CEIL((p:= p + 1) / $perpage) page
   FROM news
   ORDER BY id
)C
ON C.id = T.id
SET T.page = C.page;

现在想获取任意一页的元素就很简单了:

SELECT *
FROM news A
JOIN pagination B ON A.id=B.ID
WHERE page=$offset;

还有另外一种与上种方法比较相似的方法来做分页,这种方式比较试用于数据集相对小,并且没有可用的索引的情况下—比如处理搜索结果时。在一个普通的服务器上执行下面的查询,当有2M条记录时,要耗费2sec左右。这种方式比较简单,创建一个用来存储所有Id的临时表即可(这也是最耗费性能的地方)。

CREATE TEMPORARY TABLE _tmp (KEY SORT(random))
SELECT id, FLOOR(RAND() * 0x8000000) random
FROM city;

ALTER TABLE _tmp ADD OFFSET INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, DROP INDEX SORT, ORDER BY random;

接下来就可以向下面一样执行分页查询了。

SELECT *
FROM _tmp
WHERE OFFSET >= $offset
ORDER BY OFFSET
LIMIT $perpage;

简单来说,对于分页的优化就是。。。避免数据量大时扫描过多的记录。

以上就是MySQL分页性能优化指南的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
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架构原理图文详解mysql架构原理May 17, 2022 pm 05:54 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于架构原理的相关内容,MySQL Server架构自顶向下大致可以分网络连接层、服务层、存储引擎层和系统文件层,下面一起来看一下,希望对大家有帮助。

mysql的msi与zip版本有什么区别mysql的msi与zip版本有什么区别May 16, 2022 pm 04:33 PM

mysql的msi与zip版本的区别:1、zip包含的安装程序是一种主动安装,而msi包含的是被installer所用的安装文件以提交请求的方式安装;2、zip是一种数据压缩和文档存储的文件格式,msi是微软格式的安装包。

mysql怎么去掉第一个字符mysql怎么去掉第一个字符May 19, 2022 am 10:21 AM

方法:1、利用right函数,语法为“update 表名 set 指定字段 = right(指定字段, length(指定字段)-1)...”;2、利用substring函数,语法为“select substring(指定字段,2)..”。

mysql怎么替换换行符mysql怎么替换换行符Apr 18, 2022 pm 03:14 PM

在mysql中,可以利用char()和REPLACE()函数来替换换行符;REPLACE()函数可以用新字符串替换列中的换行符,而换行符可使用“char(13)”来表示,语法为“replace(字段名,char(13),'新字符串') ”。

mysql怎么将varchar转换为int类型mysql怎么将varchar转换为int类型May 12, 2022 pm 04:51 PM

转换方法:1、利用cast函数,语法“select * from 表名 order by cast(字段名 as SIGNED)”;2、利用“select * from 表名 order by CONVERT(字段名,SIGNED)”语句。

MySQL复制技术之异步复制和半同步复制MySQL复制技术之异步复制和半同步复制Apr 25, 2022 pm 07:21 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于MySQL复制技术的相关问题,包括了异步复制、半同步复制等等内容,下面一起来看一下,希望对大家有帮助。

mysql怎么判断是否是数字类型mysql怎么判断是否是数字类型May 16, 2022 am 10:09 AM

在mysql中,可以利用REGEXP运算符判断数据是否是数字类型,语法为“String REGEXP '[^0-9.]'”;该运算符是正则表达式的缩写,若数据字符中含有数字时,返回的结果是true,反之返回的结果是false。

mysql怎么删除unique keymysql怎么删除unique keyMay 12, 2022 pm 03:01 PM

在mysql中,可利用“ALTER TABLE 表名 DROP INDEX unique key名”语句来删除unique key;ALTER TABLE语句用于对数据进行添加、删除或修改操作,DROP INDEX语句用于表示删除约束操作。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft