oracle查询使用伪列ROWNUM

时间:2014-02-20 09:27:50

标签: oracle

SELECT SOME_COLUMN_NAME_1
FROM (
      SELECT ROWNUM rnum, SOME_COLUMN_NAME_1
      FROM SOME_TABLE_NAME
      ORDER BY ROWID
)
WHERE rnum between 20001 and 30000

给了我rownum 20001和30000之间的10000行,没有在rownum列上排序

SELECT SOME_COLUMN_NAME_1 
FROM ( 
       SELECT ROWNUM rnum,a.SOME_COLUMN_NAME_1 
       FROM (
            SELECT SOME_COLUMN_NAME_1 
            FROM  SOME_TABLE_NAME
       ) a
)
WHERE rnum BETWEEN 20001 AND 30000

在rownum 20001和30000之间给出了10000行,在rownum列

上排序

PLZ解释

1 个答案:

答案 0 :(得分:1)

线索在于here

Oracle ROWID唯一标识行驻留在磁盘上的位置。 ROWID中的信息为Oracle提供了查找行所需的所有内容,磁盘编号,柱面,块和偏移量。

Rownum是一个伪列。它并不总是与记录有关。它只是按照获取的顺序依次分配的数字。

ROWNUM和ROWID之间的区别在于ROWNUM是临时的,而ROWID是永久性的。另一个区别是ROWID可用于获取行,而ROWNUM仅在单个SQL语句的上下文中有意义,这是一种在获取的结果集中引用行的方法。

所以在你的第一个查询中,当你通过rowid订购然后按rownum过滤时,你会得到一个

SELECT SOME_COLUMN_NAME_1
FROM (
      SELECT ROWNUM rnum, SOME_COLUMN_NAME_1
      FROM SOME_TABLE_NAME
      ORDER BY ROWID
)
WHERE rnum between 20001 and 30000

-- Rows fetched first and assinged a sequence 1,2,...N 
-- they are ordered by rowid (address of the record) make 
-- it a scrambled arrangement

在第二个查询中,

SELECT SOME_COLUMN_NAME_1 
FROM ( 
       SELECT ROWNUM rnum,a.SOME_COLUMN_NAME_1 
       FROM (
            SELECT SOME_COLUMN_NAME_1 
            FROM  SOME_TABLE_NAME
       ) a
)
WHERE rnum BETWEEN 20001 AND 30000;

-- You select a set of rows (Order is preserved)
-- assign a sequence using rownum (Still order is preserved)