Rownum:
rownum是 oracle 中的伪列,并不真正存在于表中,它只在查询的时候产生。也就是说表中的数据并没有一个真正的物理的列去表示一条记录是第几行,而只是在查询中才会对这些行进行标识。那到底rownum是什么时候赋给行的呢?
rownum是在where条件过滤之后,在任何排序(order by)或聚集(aggregation)之前赋给行的。
同时,只有当rownum被分配给行后才会递增。
rownum的初始值为1。rownum在查询中产生后就不再变化
rownum被分配的过程大致如下:
rownum = 1
for x in ( select * from A )
loop
if ( x satisifies the predicate )
then
OUTPUT the row
rownum = rownum + 1
end if;
end loop;
而一个查询的执行顺序大概是这样的:
Select …, ROWNUM
From t
Where <where clause>
Group by <columns>
Having <having clause>
Order by <columns>
Think of it as being processed in this order:
1.The FROM and WHERE clause go first.
2.ROWNUM is assigned and incremented to each output row from the FROM/WHERE.
3.SELECT is applied.
4.GROUP BY is applied.
5.HAVING is applied.
6.It is sorted.
根据以上规则,我们可对如下的语句进行解释:
1。select * from t where ROWNUM > 1
当执行该语句时,第一条记录rownum=1,此时不满足rownum >1的条件,所以返回零条记录。
2。select * from t where ROWNUM = 1
该语句会返回1行记录,因为第一条记录rownum=1,满足rownum=1这个条件。
3。select * from t where ROWNUM<5
该语句会返回4行记录。第一行记录rownum=1,满足ROWNUM<5这个条件,此时ROWNUM递增1,然后继续比较,直到ROWNUM=4,循环结束。
4。select * from t where ROWNUM>=1
同理该语句会返回所有记录。
5。select * from emp where ROWNUM <= 5 order by sal desc;
该语句的目的是想返回top 5薪水最高的员工信息,但根据rownum的产生原理,rownum在order by之前就已经产生,所以该语句并不能起到top 5的作用,正确的语法如下:
select * from (select * from emp order by sal desc) where ROWNUM <= 5;
另外,关于rownum可参考asktom的两篇文章:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:948366252775
No Comments
Be the first to comment on this entry.
Leave a comment
Fields in bold are required. Email addresses are never published or distributed.
Some HTML code is allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>URLs must be fully qualified (eg: http://www.dbifan.com),and all tags must be properly closed.
Line breaks and paragraphs are automatically converted.
Please keep comments relevant. Off-topic, offensive or inappropriate comments may be edited or removed.