原文地址:http://blog.csdn.net/yejr/article/details/70039403
在开发项目的过程中随时可能遇到深度分页的情况,比如:
select * from table order by id desc limit 200000,10;
如果explain这个语句,结果是这样
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | |
---|---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | yd_stock | ALL | NULL | NULL | NULL | NULL | 233355 | Using filesort |
没有使用任何的索引,全表扫描了20万数据。这个就会使查询的效率下降,针对这种情况可以优化。
推荐使用inner join,比如将sql改成
select * from table a inner join (select id from table order by id desc limit 200000,10) b using(id)
这个sql的执行耗时比上一个提高了几十倍。explain后面的子句
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | |
---|---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | yd_stock | index | NULL | PRIMARY | 3 | NULL | 200010 | Using index |
使用了主键索引,所以这个查询会很快,自然整个语句的执行速度就上去了