ROWNUM

来源:互联网 发布:水电改造设计软件 编辑:程序博客网 时间:2024/05/16 01:09

1、rownum是oracle系统顺序分配为从查询返回的行的编号,返回的第一行分配的是1,第二行是2,依此类推,这个伪字段可以用于限制查询返回的总行数。

2、rownum不能以任何基表的名称作为前缀。

在Oracle中,要按特定条件查询前N条记录,用个rownum就搞定了。

select * from emp where rownum <= 5

而且书上也告诫,不能对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.

了解了原理,就知道rownum>不会成功,因为在第三步的时候查询出的行已经被丢弃,第四步查出来的rownum仍然是1,这样永远也不会成功。
同样道理,rownum如果单独用=,也只有在rownum=1时才有用。

此外,介绍下select的执行顺序:

1、from子句组装来自不同数据源的数据;

2、where子句基于指定的条件对记录行进行筛选;

3、group by子句将数据划分为多个分组;

4、使用聚集函数进行计算;

5、使用having子句筛选分组;

6、计算所有的表达式;

7、select 的字段;

8、使用order by对结果集进行排序。

由以上信息得可以,想通过rownum=1获取得排序后的值是不正确的;如想获取排序后的第一个值,应该将排序后的结果作为子集,然后再对子集进行查询时使用rownum。


0 0