问题
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