How can I speed up a MySQL query with a large offset in the LIMIT clause?(如何在 LIMIT 子句中使用大偏移量加速 MySQL 查询?)
问题描述
我在 LIMIT 使用大偏移量的 mysql SELECT 时遇到性能问题:
I'm getting performance problems when LIMITing a mysql SELECT with a large offset:
SELECT * FROM table LIMIT m, n;
如果偏移量 m 大于 1,000,000,则操作非常慢.
If the offset m is, say, larger than 1,000,000, the operation is very slow.
我必须使用 limit m, n;我不能使用诸如 id > 之类的东西.1,000,000 个限制 n.
I do have to use limit m, n; I can't use something like id > 1,000,000 limit n.
如何优化此语句以获得更好的性能?
How can I optimize this statement for better performance?
推荐答案
也许您可以创建一个索引表,它提供与目标表中的键相关的顺序键.然后,您可以将此索引表连接到目标表,并使用 where 子句更有效地获取所需的行.
Perhaps you could create an indexing table which provides a sequential key relating to the key in your target table. Then you can join this indexing table to your target table and use a where clause to more efficiently get the rows you want.
#create table to store sequences
CREATE TABLE seq (
seq_no int not null auto_increment,
id int not null,
primary key(seq_no),
unique(id)
);
#create the sequence
TRUNCATE seq;
INSERT INTO seq (id) SELECT id FROM mytable ORDER BY id;
#now get 1000 rows from offset 1000000
SELECT mytable.*
FROM mytable
INNER JOIN seq USING(id)
WHERE seq.seq_no BETWEEN 1000000 AND 1000999;
这篇关于如何在 LIMIT 子句中使用大偏移量加速 MySQL 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 LIMIT 子句中使用大偏移量加速 MySQL 查询?
基础教程推荐
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 无法解决整理冲突 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
