不管是写存储过程,还是在应用中嵌入sql,分页查询的主要sql还是通用的,哪种方法更好用呢,自己测试了下,由于是自己笔记本测试,能有比较大的误差

准备; oracle 10.2,scott方案的emp表的拷贝版本,一共有插入了19200条数据,取的是7000到8000条。

 

 
  
  1. SQL> select count(*) from emp1; 
  2.   
  3.   COUNT(*) 
  4. ---------- 
  5.      19200 

使用rownum方法得的sql

第一种:子查询中分2次限制了条件

 
  
  1. --使用2层的条件  
  2. select * 
  3.   from (select t1.*, rownum rn 
  4.           from (select * from emp1) t1 
  5.          where rownum <=8000) t2 
  6.  where rn >= 7000;  
  7. --耗时7.875秒 

第二种:子查询中在一次用限制了条件

 
  
  1. --使用一层条件 
  2. select * 
  3.   from (select t1.*, rownum rn from (select * from emp1) t1) 
  4.  where rn between 7000 and 8000;  
  5.  --耗时13.812秒 

使用rowid的方法

第三种:看到别的人说效率最高,可是用了下没感到!!而且要用到表中的字段empno

 
  
  1. --使用rowid写分页的方法 
  2. select * 
  3.   from emp1 
  4.  where rowid in 
  5.        (select rid 
  6.           from (select rownum rn, rid 
  7.                   from (select rowid rid, empno from emp1 order by empno ) 
  8.                  where rownum < =8000) 
  9.          where rn > =7000) 
  10.  order by empno  ;   
  11. --耗时11.266秒 
  12. --!! 需要特定的字段empno,感觉不怎么灵活呢 

使用函数分析的方法

第四种:这个也要用到empno字段来筛选

 
  
  1. --使用分析函数来写 
  2. select * 
  3.   from (select t.*, row_number() over(order by empno ) rk from emp1 t) 
  4.  where rk <= 8000 
  5.    and rk >= 7000;    
  6. --耗时14.25秒 
  7. --!!也需要特定的字段来支持 

从几个时间的对比来看,还是第一种方法比较好,并且说来第三 第四种方法还要有字段的限制,不是很通用。