=## oracle使用rownum进行分页语句详解
rownum和rowid是两种不同的东西,不知道你如何利用rowid来分页?
rownum是返回的记录编号。rowid可理解为返回记录的实际地址。
当根据rowid访问时相当于不经查询直接取数,用rownum必须经过查询(即数据库里有查询动作)。如果已经知道了rowid再去获取数据和通过rownum计数去获取数据,肯定用rowid快。
实际上,由于oracle不支持的真正的分页查询,所谓分页,是先把数据从数据库中查询出来,然后再把对应页的数据返回给调用者,剩余的数据扔掉了。所以,这种情况下,注定用rowid不如用rownum快。
–第一步:
select * from emp;
–第二步:
select t1.*,rownum rn from (select * from emp) t1;
查询结果如下:rownum为oracle默认的行编号,我们以此来进行分页查询
sql> select t1.*,rownum rn from (select * from emp) t1;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO RN
----- ---------- --------- ----- ----------- --------- --------- ------ ----------
6666 itguang BOSS 1111 2017/8/1 16 0.00 0.00 40 1
7369 SMITH CLERK 7902 1980/12/17 800.00 20 2
7499 ALLEN SALESMAN 7698 1981/2/20 1600.00 300.00 30 3
7521 WARD SALESMAN 7698 1981/2/22 1250.00 500.00 30 4
7566 JONES MANAGER 7839 1981/4/2 2975.00 20 5
7654 MARTIN SALESMAN 7698 1981/9/28 1250.00 1400.00 30 6
7698 BLAKE MANAGER 7839 1981/5/1 2850.00 30 7
7782 CLARK MANAGER 7839 1981/6/9 2450.00 10 8
7788 SCOTT ANALYST 7566 1987/4/19 8888.00 20 9
7839 KING PRESIDENT 1981/11/17 5000.00 10 10
7844 TURNER SALESMAN 7698 1981/9/8 1500.00 0.00 30 11
7876 ADAMS CLERK 7788 1987/5/23 1100.00 20 12
7900 JAMES CLERK 7698 1981/12/3 950.00 30 13
7902 FORD ANALYST 7566 1981/12/3 3000.00 20 14
7934 MILLER CLERK 7782 1982/1/23 1300.00 10 15
– 第三步:查询rownum<=10的数据
select t1.*,rownum rn from (select * from emp) t1 where rownum<=10;
查询结果:
sql> select t1.*,rownum rn from (select * from emp) t1 where rownum<=10;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO RN
----- ---------- --------- ----- ----------- --------- --------- ------ ----------
6666 itguang BOSS 1111 2017/8/1 16 0.00 0.00 40 1
7369 SMITH CLERK 7902 1980/12/17 800.00 20 2
7499 ALLEN SALESMAN 7698 1981/2/20 1600.00 300.00 30 3
7521 WARD SALESMAN 7698 1981/2/22 1250.00 500.00 30 4
7566 JONES MANAGER 7839 1981/4/2 2975.00 20 5
7654 MARTIN SALESMAN 7698 1981/9/28 1250.00 1400.00 30 6
7698 BLAKE MANAGER 7839 1981/5/1 2850.00 30 7
7782 CLARK MANAGER 7839 1981/6/9 2450.00 10 8
7788 SCOTT ANALYST 7566 1987/4/19 8888.00 20 9
7839 KING PRESIDENT 1981/11/17 5000.00 10 10
10 rows selected
–第四步:查询5<=rownum<=10之间的数据
select * from (select t1.*,rownum rn from (select * from emp) t1 where rownum<=10) where rn>=5;
查询结果
sql> select * from 2 (select t1.*,rownum rn from (select * from emp) t1 where rownum<=10) 3 where rn>=5;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO RN
----- ---------- --------- ----- ----------- --------- --------- ------ ----------
7566 JONES MANAGER 7839 1981/4/2 2975.00 20 5
7654 MARTIN SALESMAN 7698 1981/9/28 1250.00 1400.00 30 6
7698 BLAKE MANAGER 7839 1981/5/1 2850.00 30 7
7782 CLARK MANAGER 7839 1981/6/9 2450.00 10 8
7788 SCOTT ANALYST 7566 1987/4/19 8888.00 20 9
7839 KING PRESIDENT 1981/11/17 5000.00 10 10
6 rows selected
完整oracle分页语句
select * from (select t1.*,rownum rn from (select * from emp) t1 where rownum<=10) where rn>=5;