不管是写存储过程,还是在应用中嵌入sql,分页查询的主要sql还是通用的,哪种方法更好用呢,自己测试了下,由于是自己笔记本测试,能有比较大的误差
准备; oracle 10.2,scott方案的emp表的拷贝版本,一共有插入了19200条数据,取的是7000到8000条。
- SQL> select count(*) from emp1;
- COUNT(*)
- ----------
- 19200
使用rownum方法得的sql
第一种:子查询中分2次限制了条件
- --使用2层的条件
- select *
- from (select t1.*, rownum rn
- from (select * from emp1) t1
- where rownum <=8000) t2
- where rn >= 7000;
- --耗时7.875秒
第二种:子查询中在一次用限制了条件
- --使用一层条件
- select *
- from (select t1.*, rownum rn from (select * from emp1) t1)
- where rn between 7000 and 8000;
- --耗时13.812秒
使用rowid的方法
第三种:看到别的人说效率最高,可是用了下没感到!!而且要用到表中的字段empno
- --使用rowid写分页的方法
- select *
- from emp1
- where rowid in
- (select rid
- from (select rownum rn, rid
- from (select rowid rid, empno from emp1 order by empno )
- where rownum < =8000)
- where rn > =7000)
- order by empno ;
- --耗时11.266秒
- --!! 需要特定的字段empno,感觉不怎么灵活呢
使用函数分析的方法
第四种:这个也要用到empno字段来筛选
- --使用分析函数来写
- select *
- from (select t.*, row_number() over(order by empno ) rk from emp1 t)
- where rk <= 8000
- and rk >= 7000;
- --耗时14.25秒
- --!!也需要特定的字段来支持
从几个时间的对比来看,还是第一种方法比较好,并且说来第三 第四种方法还要有字段的限制,不是很通用。
转载于:https://blog.51cto.com/orangleliu/1066911