oracle rownum 使用注意事项

2008 年 06 月 13 日 上午 9:07 | | 阅读次数 : 3,968 次 | 数据库 | ,


Please Note: This post is over a year old, any information within it may be out-of-date.

在Oracle中,要按特定条件查询前N条记录,用个rownum就搞定了。 select * from emp where rownum <= 5
那我要取N记录之后的呢?是不是rownum用”>” 即 select * from emp where rownum > 5 就搞定了呢??
答案是否定的!
先看看rownum的使用规则:

1 Oracle executes your query.
2 Oracle fetches the first row and calls it row number 1.
3 Have we gotten past row number meets the criteria? If no, then Oracle discards the row, If yes, then Oracle return the row.
4 Oracle fetches the next row and advances the row number (to 2, and then to 3, and then to 4, and so forth).
5 Go to step 3.

就想java的类rowset一样,使用过后,查询出的行已经被丢弃,所以,这样不能持久的使用。所以,只有在rownum=1时才有用。  

对于rownum来说它是oracle系统顺序分配为从查询返回的行的编号,返回的第一行分配的是1,第二行是2,依此类推,这个伪字段可以用于限制查询返回的总行数,而且rownum不能以任何表的名称作为前缀。

设定一个表company,有13行记录,要查3到10行,怎么查呢?都知道在mysql里面有limit,很好用,在oracle时就要使用子查询了。

如:
SELECT * FROM (SELECT ROWNUM NO FROM COMPANY) WHERE NO BETWEEN 3 AND 10
这样就ok了,如使用
SELECT ROWNUM FROM COMPANY WHERE ROWNUM BETWEEN 3 AND 10
这样就是不对的。很小的问题,大家记住。:)

Share

Leave a Reply

Your email address is never published nor shared. Required fields are marked with a *.


(必填)

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

注意: 评论者允许使用'@user空格'的方式将自己的评论通知另外评论者。例如, ABC是本文的评论者之一,则使用'@ABC '(不包括单引号)将会自动将您的评论发送给ABC。