今天刚好在网上看到一篇关于rownum和order by的文章
英文的,大概意思就是说
SELECT firstname
FROM employee
WHERE ROWNUM < 5
ORDER BY empid
empid如果是主键,这个语句可以返回期望的结果,按empid排序且rownum也是升序排列
如果order by的字段不是主键,返回的结果按empid排序但rownum的顺序是乱的,和插入DB的时间有关
原文及出处
http://www.devx.com/tips/Tip/14251
Using ROWNUM Pseudocolumn in Oracle
When querying in Oracle, use ROWNUM pseudocolumn to limit the number of returned rows. Pseudocolumns behave like table columns but are not actually stored in tables. (Other pseudocolumns are RowId, Level, etc.).
In Sybase, the equivalent way to restrict returned rows in T-SQL is the following:
Set Rowcount n
Where 'n' stands for number of rows returned by queryConsider following this example, which would restrict the resulting number of rows to 9:
SELECT firstname
FROM employee
WHERE ROWNUM < 10 ;Here are the results:
FIRSTNAME
------------
John
Tim
Julie
Stacy
Rahul
Leena
Amy
Bill
TeriHowever, one should be careful when using the Order By clause along with Rownum. When Order By is used with Rownum to restrict query results, it works only if Ordered By is the primary key of the table. For example, empid is the primary key in this employee table:
SELECT firstname
FROM employee
WHERE ROWNUM < 5
ORDER BY empid;Here are the results:
FIRSTNAME
------------
John
Julie
Stacy
TimNow consider the following query, ordered by a non-PK column. The order of its results would be unpredictable. It would depend on how the rows were inserted in table.
SELECT firstname
FROM employee
WHERE ROWNUM< 5
ORDER BY firstname;Here are the results:
FIRSTNAME
------------
Teri
Julie
Stacy
Bill
本文探讨了在Oracle数据库中使用ROWNUM伪列限制查询结果数量的方法,并讨论了ROWNUM与ORDER BY结合使用时的不同行为表现。当ORDER BY后的字段为表的主键时,查询结果将按主键有序排列;若非主键,则结果的ROWNUM顺序可能受数据插入时间影响而变得不可预测。
3241

被折叠的 条评论
为什么被折叠?



