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