明确对于rownum 来说它是oracle系统顺序分配为从查询返回的行的编号,返回的第一行分配的是1,第二行是二,以此类推,这个为字段可以用于限制查询的返回的总行数,因为rownum总是从1开始,但是1以上的自然数在rownum 做等于判断时都认为是false 条件,所以无法查到 rownum=n (n》1的自然数),所以查找第二行以后的记录可以用子查询方法来解决,给子查询中的rownum取别名;对于小于某个值的情况两种方法都差不多,但是对于某个不等于一的值或者求某个值到某个值之间的情况,用row_number() 别名获得排名 ,比用rownum伪列要简单方便的多;因为伪列总是从一开始查找;
具体用法和区别参见以下代码;
--取出工资最高的前5位
1
2
3
4
|
select empno,ename,sal,rownum from emp; select * from ( select * from emp order by sal desc ) where rownum<=5; select * from ( select ename,sal,row_number() over( order by sal desc ) as num from emp) where num<=5; select * from ( select ename,sal,row_number() over( order by sal desc ) from emp) where rownum<=5 |
--工资的前3名
1
2
3
4
|
select * from emp where sal >= any ( select * from ( select sal from emp order by sal desc ) where rownum<=3); select * from ( select * from emp order by sal desc ) where rownum <4; select * from ( select ename,sal,empno,deptno ,row_number() over ( order by sal desc ) from emp) where rownum<4; select * from ( select ename,sal,empno,deptno ,row_number() over ( order by sal desc ) as num from emp) where num<4 |
--按照工资排序,取出第6名到第10名
--使用伪列获得
1
|
select * from ( select ename,sal,rownum r from ( select * from emp order by sal desc ) where rownum<=10) where r>5; |
--使用排名函数获得
1
|
select * from ( select ename,sal,row_number() over( order by sal desc ) as num from emp) where num>5 and num<=10; |
------- 按工资从高到低获得工资排名第四的员工
1
2
|
select * from ( select ename,sal,row_number() over( order by sal desc ) as num from emp) where num=4; select * from ( select ename,sal,rownum r from ( select * from emp order by sal desc ) where rownum<=4) where r=4; |
总结oracle中rownum和row_number()的区别
row_number()是分析函数,基本语法为row_number() over(partition by 字段 order by 字段)
rownum是一个伪列
1
2
3
4
|
select * from dept where rownum<=3; select * from dept where rownum between 2 and 3;这儿会出错,因为rownum的特性(没有1就不会有2,没有3)决定的 SELECT * FROM ( SELECT A.*,ROWNUN FROM DEPT A)T1 WHERE T1.ROWNUM BETWEEN 2 AND 3;这么写不对,要这样写 SELECT * FROM ( SELECT A.*,ROWNUM RN FROM DEPT A)T1 WHERE T1.RN BETWEEN 2 AND 3; |
他们的主要区别是:使用rownum进行排序的时候是先对结果集加入伪列rownum然后再进行排序,而函数row_number()在包含排序从句后是先排序再计算行号码。