通常分页查询的时候会使用这样的语句:
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很大,也是获取了很多的主键,而不是所有的字段数据,相对而言效率会提升很多。
相关推荐:
mysql优化总结-查询总条数
常用mysql优化sql语句查询方法汇总
mysql优化包括的三个方面
以上就是mysql分页时offset过大的sql优化实例分享的详细内容。