日期:2014-05-16  浏览次数:20488 次

索引优化分页
原sql:
select * from (
         select a.*,rownum rn from
                   (select * from product a where company_id=? order by status) a
         where rownum<=20)
where rn>10;
优化:
优化原理是通过纯索引找出分页记录的ROWID,再通过ROWID回表返回数据,要求内层查询和排序字段全在索引里。
create index myindex on product(company_id,status);

select b.* from (
         select * from (
                   select a.*,rownum rn from
                            (select rowid rid,status from product a where company_id=? order by status) a
                   where rownum<=20)
         where rn>10) a, product b
where a.rid=b.rowid;
数据访问开销=索引IO+索引分页结果对应的表数据IO

实例:
一个公司产品有1000条记录,要分页取其中20个产品,假设访问公司索引需要50个IO,2条记录需要1个表数据IO。
那么按第一种ROWNUM分页写法,需要550(50+1000/2)个IO,按第二种ROWID分页写法,只需要60个IO(50+20/2);