使用子查询优化大数据量分页查询
这种方式的做法是先定位偏移位置的id,然后再往后查询,适用于id递增的情况。
select * from orders_history where type = 8 limit 100000,1;
select id from orders_history where type = 8 limit 100000,1;
select * from orders_history where type = 8 and id >= (
select id from orders_history where type = 8 limit 100000,1
) limit 100;
select * from orders_history where type = 8 limit 100000,100;
查询的方法是先使用范围查询定位id(或者索引),然后再使用索引进行定位数据,就能够提高好几倍查询速度。即先select id,然后再select *。
使用id限定优化大数据量分页查询
使用这种方式需要先假设数据表的id是连续递增的,我们根据查询的页数和查询的记录数可以算出查询的id的范围,可以使用 id between and 来查询:
select *
from orders_history
where type = 2
and (id between 1000000 and 1000100)
limit 100;
select * from orders_history where id >= 1000001 limit 100;
当然了,也可以使用in的方式来进行查询,这种方式经常用在多表关联的情况下,使用其他表查询的id集合来进行查询:
select * from orders_history where id in (
select order_id from trade where good_name = 'apple'
) limit 100;
但是使用这种in查询方式的时候要注意的是,某些MySQL版本并不支持在in子句中使用limit子句。
网友评论