SQL (ORACLE): ORDER BY and LIMIT

。_饼干妹妹 提交于 2019-11-26 05:32:55

问题


I want do sorting by property ALL data in my db and ONLY AFTER that use LIMIT and OFFSET.

Query like this:

SELECT select_list
    FROM table_expression
    [ ORDER BY ... ]
    [ LIMIT { number | ALL } ] [ OFFSET number ] 

I know the sorting ends as soon as it has found the first row_count rows of the sorted result. Can I do sorting all data before calling LIMIT and OFFSET?


回答1:


Prior to 12.1, Oracle does not support the LIMIT or OFFSET keywords. If you want to retrieve rows N through M of a result set, you'd need something like:

SELECT a.*
  FROM (SELECT b.*,
               rownum b_rownum
          FROM (SELECT c.*
                  FROM some_table c
                 ORDER BY some_column) b
         WHERE rownum <= <<upper limit>>) a
 WHERE b_rownum >= <<lower limit>>

or using analytic functions:

SELECT a.*
  FROM (SELECT b.*,
               rank() over (order by some_column) rnk
          FROM some_table)
 WHERE rnk BETWEEN <<lower limit>> AND <<upper limit>>
 ORDER BY some_column

Either of these approaches will sort give you rows N through M of the sorted result.

In 12.1 and later, you can use the OFFSET and/or FETCH [FIRST | NEXT] operators:

SELECT *
  FROM some_table
 ORDER BY some_column
 OFFSET <<lower limit>> ROWS
  FETCH NEXT <<page size>> ROWS ONLY


来源:https://stackoverflow.com/questions/7480243/sql-oracle-order-by-and-limit

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