problem with rownum

核能气质少年 提交于 2019-12-10 12:04:21

问题


I have a query

select * from tablename where rownum =1;

This query is giving desired result but if i run

select * from tablename where rownum=2;

Then this query is giving null result. Any idea why?


回答1:


The predicate WHERE rownum=2 can never be true because of the way ROWNUM is assigned. If there are 5 rows in the table, for example, the algorithm would go something like

  • Retrieve the first row from the table. Assign it a rownum of 1.
  • Check this rownum against the predicate, discard
  • Retrieve the second row from the table. Assign it a rownum of 1.
  • Check this rownum against the predicate, discard
  • Retrieve the third row from the table. Assign it a rownum of 1.
  • Check this rownum against the predicate, discard
  • Retrieve the fourth row from the table. Assign it a rownum of 1.
  • Check this rownum against the predicate, discard
  • Retrieve the fifth row from the table. Assign it a rownum of 1.
  • Check this rownum against the predicate, discard

Since there is no "first row" in the result set, there can be no "second row". You can use ROWNUM in inequality comparisons, i.e.

SELECT *
  FROM table_name
 WHERE rownum <= 2

will return 2 rows.

If you are trying to identify the "second row" in a table, you'd likely want something like

SELECT *
  FROM (SELECT t.*,
               rank() over (order by some_column) rnk
          FROM table_name)
 WHERE rnk = 2



回答2:


I don't think this is a well defined query:

ROWNUM is a pseudo-column that returns a row's position in a result set. ROWNUM is evaluated AFTER records are selected from the database and BEFORE the execution of ORDER BY clause.



来源:https://stackoverflow.com/questions/6441329/problem-with-rownum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!