简体   繁体   English

在oracle SQL语句中结合order by子句使用rownum

[英]Using rownum in oracle SQL statement in combination with order by clause

Which of the following two SQL statements will return the desired result set (ie the ten rows with Status=0 and the highest StartTimes)? 以下两个SQL语句中的哪一个将返回所需的结果集 (即具有Status = 0和最高StartTimes的十行)?

Will both statements always return the same result set (StartTime is unique)? 两个语句是否总是返回相同的结果集 (StartTime是唯一的)?

SELECT * 
FROM MyTable 
WHERE Status=0 
AND ROWNUM <= 10 
ORDER BY StartTime DESC

SELECT * 
FROM (
    SELECT * 
    FROM MyTable 
    WHERE Status=0 
    ORDER BY StartTime DESC
) 
WHERE ROWNUM <= 10

Background 背景

My DBAdmin told me that the first statement will first limit the table to 10 rows and than order those random rows by StartTime, which is definitly not what I want. 我的DBAdmin告诉我,第一个语句将首先将表限制为10行,而不是按StartTime对这些随机行进行排序,这绝对不是我想要的。 From what I learned in that answer , the order by clause of the second statement is redundant and could be removed by an optimizer, which is also not what I want. 根据我在该答案中学到的内容第二个语句的order by子句是多余的,可以通过优化器删除,这也不是我想要的。


I asked a similar question concering the limit clause in a query to a SQLite database and am interested in understanding any differences to the above statements (using limit Vs rownum ) used with an oracle db. 我问了一个类似的问题 ,在对SQLite数据库的查询中隐含了limit子句,并且有兴趣理解与oracle db一起使用的上述语句(使用limit Vs rownum )的任何差异。

Your Second Query will work 您的第二个查询将起作用

Because in the first ,the first ten rows with Status 0 are selected and then the order by is done in that case the first ten rows fetched need not be in the highest order 因为在第一个中,选择了具有状态0的前十行,然后在这种情况下完成了顺序,所获取的前十行不需要处于最高顺序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM