MySQL LIMIT 的性能问题

有个几千万条记录的表 on MySQL 5.0.x,现在要读出其中几十万万条左右的记录

常用方法,依次循环:
select * from mytable where index_col = xxx limit offset, limit;

经验:如果没有blob/text字段,单行记录比较小,可以把 limit 设大点,会加快速度
问题:头几万条读取很快,但是速度呈线性下降,同时 mysql server cpu 99%
速度不可接受。

调用 explain select * from mytable where index_col = xxx limit offset, limit;
显示 type = ALL

在 MySQL optimization 的文档写到"All"的解释
A full table scan is done for each combination of rows from the previous tables. This is normally not good if the table is the first table not marked const, and usually very bad in all other cases. Normally, you can avoid ALL by adding indexes that allow row retrieval from the table based on constant values or column values from earlier tables.

看样子对于 all, mysql 就使用比较笨的方法,那就改用 range 方式?

因为 id 是递增的,也很好修改 sql

select * from mytable where id > offset and id < offset + limit and index_col = xxx

explain 显示 type = range, 结果速度非常理想,返回结果快了几十倍。 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值