查询“限制”不返回结果

时间:2013-03-05 12:24:21

标签: sql oracle

这是我的疑问:

select * 
  from (SELECT "MYTABLE".* FROM "MYTABLE" ORDER BY "COMPANY" ASC, "SURNAME" ASC) 
 where ROWNUM between 0 and 20

哪个像预期的那样工作,但是当我尝试用以下内容获取接下来的20个记录时

select * 
  from (SELECT "MYTABLE".* FROM "MYTABLE" ORDER BY "COMPANY" ASC, "SURNAME" ASC) 
 where ROWNUM between 20 and 40

结果集是空的?为什么这样做以及如何才能获得接下来的20条记录呢?

1 个答案:

答案 0 :(得分:4)

你必须嵌套rownum,因为只有在获取行时rownum才会递增。所以说rownum > 1永远不会返回一行。 例如

select *
  from (select a.*, rownum r 
          from (select mytable.*
                  from mytable 
                 order by company asc, surname asc) a
         where rownum <= 40
       )
 where r >= 20
 order by r;

或者您可以使用row_number()分析

select *
  from (select mytable.*, row_number() over (order by company asc, surname asc) rn
          from mytable) 
 where rn between 20 and 40
 order by rn;