关于rownum的一点体会

ROWNUM是一个“伪列“,数据库中并不保存ROWNUM列的值。当某一行记录读入内存时,相应的ROWNUM才被动态地赋值,用以纪录该条记录位于结果集中的第几行。对于同一条记录,每次返回时ROWNUM值都可能不同。

[@more@] 可以用下面的小测试来验证:
SQL> connect scott/tiger
Connected to Oracle Database 10g Enterprise Edition Release 10.1.0.2.0
Connected as scott

SQL> select rownum,deptno,dname from dept;
ROWNUM DEPTNO DNAME
---------- ------ --------------
1 10 ACCOUNTING
2 20 RESEARCH
3 30 SALES
4 40 OPERATIONS

在上述结果中,DEPTNO=30的记录,其ROWNUM=3,而在下面的结果中,DEPTNO=30的记录,其ROWNUM=1。
SQL> select rownum, deptno,dname from dept where deptno=30;
ROWNUM DEPTNO DNAME
---------- ------ --------------
1 30 SALES

所以,在select中,只有 rownum条件为"","=",">="都不能返回结果。
SQL> select rownum, deptno,dname from dept where rownum<3;
ROWNUM DEPTNO DNAME
---------- ------ --------------
1 10 ACCOUNTING
2 20 RESEARCH

SQL> select rownum, deptno,dname from dept where rownum<=3;
ROWNUM DEPTNO DNAME
---------- ------ --------------
1 10 ACCOUNTING
2 20 RESEARCH
3 30 SALES


SQL> select rownum, deptno,dname from dept where rownum=3;
ROWNUM DEPTNO DNAME
---------- ------ --------------

SQL> select rownum, deptno,dname from dept where rownum>3;
ROWNUM DEPTNO DNAME
---------- ------ --------------

SQL> select rownum, deptno,dname from dept where rownum>=3;
ROWNUM DEPTNO DNAME
---------- ------ --------------

可以利用rownum实现在结果集中提取指定行纪录,这一功能在做报表按页显示结果是很有用。
比如要显示结果集中的6到10行,可以用如下sql:
SQL> select rn, empno,ename from (select rownum rn,empno,ename from emp where rownum<=10) where rn>5;
RN EMPNO ENAME
---------- ----- ----------
6 7698 BLAKE
7 7782 CLARK
8 7788 SCOTT
9 7839 KING
10 7844 TURNER

另外,对于rownum和order by的关系,由于oracle先给rownum赋值,再做排序,则对于同样的select语句,在不同的order by情况下,某条记录的rownum值是不变的。

比如不加order by子句,
SQL> select rownum,deptno,dname,loc from dept;

ROWNUM DEPTNO DNAME LOC
---------- ---------- -------------- -------------
1 10 ACCOUNTING NEW YORK
2 20 RESEARCH DALLAS
3 30 SALES CHICAGO
4 40 OPERATIONS BOSTON

则对同样条件的select, rownum=1的纪录永远是deptno=10,rownum=2对应deptno=20......

无论order by什么字段,这种对应关系都不会变化。
SQL> select rownum,deptno,dname,loc from dept order by dname;

ROWNUM DEPTNO DNAME LOC
---------- ---------- -------------- -------------
1 10 ACCOUNTING NEW YORK
4 40 OPERATIONS BOSTON
2 20 RESEARCH DALLAS
3 30 SALES CHICAGO

SQL> select rownum,deptno,dname,loc from dept order by loc;

ROWNUM DEPTNO DNAME LOC
---------- ---------- -------------- -------------
4 40 OPERATIONS BOSTON
3 30 SALES CHICAGO
2 20 RESEARCH DALLAS
1 10 ACCOUNTING NEW YORK

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/207/viewspace-806618/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/207/viewspace-806618/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值