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