MySQL分页查询offset过大,Sql优化经验

低性能版

SELECT
*
FROM table
where condition1 = 0
and condition2 = 0
and condition3 = -1
and condition4 = -1
order by id asc
LIMIT 2000 OFFSET 50000

当offset特别大时,这条语句的执行效率会明显减低,并且效率是随着offset的增大而下降的。
缘由为:
MySQL并非跳过offset行,而是取offset+N行,而后返回放弃前offset行,返回N行,当offset特别大,而后单条数据也很大的时候,每次查询须要获取的数据就越多,天然就会很慢。性能

优化版本

SELECT
*
FROM table
JOIN
(select id from table
where condition1 = 0
and condition2 = 0
and condition3 = -1
and condition4 = -1
order by id asc
LIMIT 2000 OFFSET 50000)
as tmp using(id)

或者优化

SELECT a.* FROM table a, 
(select id from table
where condition1 = 0
and condition2 = 0
and condition3 = -1
and condition4 = -1
order by id asc
LIMIT 2000 OFFSET 50000) b 
where a.id = b.id

先获取主键列表,再经过主键查询目标数据,即便offset很大,也是获取了不少的主键,而不是全部的字段数据,相对而言效率会提高不少。code

相关文章
相关标签/搜索