首页 > 代码库 > oracle rownum对排序的影响

oracle rownum对排序的影响

1. 标准的rownum分页查询使用方法:

    select *
      from (select c.*, rownum rn from content c)
     where rn >= 1
       and rn <= 5


    2. 但是如果, 加上order by addtime 排序则数据显示不正确

    select *
      from (select c.*, rownum rn from content c order by addtime)
     where rn >= 1
       and rn <= 5


    解决方法,再加一层查询,则可以解决,

    select *
      from (select rownum rn, t.*
              from (select title, addtime from content order by addtime desc) t)
     where rn >= 1
       and rn <= 5

    如果要考虑到效率的问题,上面的还可以优化成(主要两者区别)

    select *
      from (select rownum rn, t.*
              from (select title, addtime from content order by addtime desc) t
             where rownum <= 10)
     where rn >= 3

oracle rownum对排序的影响