最近有个需求,让把db里面某张符合条件的数据都load出来,数据量略大,当然不能一次都拉出来,那自然就想到了limit,sql如下
select *
from my_table
WHERE point_type=1003
order by id limit 0,200
point_type 就是一个不带索引的普通字段
先是limit 0,1000 然后就是上一批数据的最大id,再次limit
但是很快就发生了问题,当offset很大的时候,sql基本就卡死了。
select *
from my_table
WHERE point_type =1003
limit 900000,200
-- 耗时 3181
网上查了一点资料 - 阿里巴巴的java开发手册
sql改成了如下:
select a.*
from my_table a
right join (
select id
from my_table
WHERE point_type =1003
limit 900000,200
) b
on a.id = b.id
-- 680 ms
select a.*
from my_table a ,
(
select id
from my_table
WHERE point_type =1003
limit 900000,200
) b
where a.id = b.id
-- 690 ms
确实有优化,但是不管是on 还是 where ,时间还是有点长
改成如下,耗时降低到6ms。而且 point_type 这个字段上并没有索引(当然id上是有索引的)
select *
from my_table
WHERE id > 9427596100 and point_type=1003
limit 1000
-- 6ms
当然这个9427596100,是上一次查询的时候,返回的最后一条数据的id
参考资料
sql的连接
https://www.runoob.com/mysql/mysql-join.html
https://blog.csdn.net/Kermit_father/article/details/85937406