Home  >  Article  >  Database  >  ORACLE中用rownum分页并排序的SQL语句

ORACLE中用rownum分页并排序的SQL语句

WBOY
WBOYOriginal
2016-06-07 15:21:081230browse

ORACLE中用rownum分页并排序的SQL语句 以前分页习惯用这样的SQL语句: select * from(selectt.*,rownum row_num frommytable t order by t.id) bwhere b.row_num between 1 and 10 结果发现由于该语句会先生成rownum 后执行order by 子句,因而排序结果根本不

ORACLE中用rownum分页并排序的SQL语句
以前分页习惯用这样的SQL语句:

select * from
(selectt.*,rownum row_num frommytable t order by t.id) b
where b.row_num between 1 and 10

结果发现由于该语句会先生成rownum 后执行order by 子句,因而排序结果根本不对,后来在GOOGLE上搜到一篇文章,原来多套一层select 就能很好的解决该问题,特此记录,语句如下:

select * from
(selecta.*,rownum row_num from
(select* from mytable t order by t.id desc) a
) b
where b.row_num between 1 and 10


==== 参考 ====

http://yangtingkun.itpub.net/post/468/100278

Oracle的分页查询语句基本上可以按照本文给出的格式来进行套用。分页查询格式:

SELECT * FROM
(
SELECTA.*, ROWNUM RN
FROM(SELECT * FROM TABLE_NAME) A
WHEREROWNUM = 21

其中最内层的查询SELECT * FROM TABLE_NAME表示不进行翻页的原始查询语句。ROWNUM = 21控制分页查询的每页的范围。

上面给出的这个分页查询语句,在大多数情况拥有较高的效率。分页的目的就是控制输出结果集大小,将结果尽快的返回。在上面的分页查询语句中,这种考虑主要体现在WHERE ROWNUM

选择第21 到40条记录存在两种方法,一种是上面例子中展示的在查询的第二层通过ROWNUM

SELECT * FROM
(
SELECTA.*, ROWNUM RN
FROM(SELECT * FROM TABLE_NAME) A
)
WHERE RN BETWEEN 21 AND 40

SELECT * FROM
(
SELECTA.*, ROWNUM RN
FROM(SELECT * FROM TABLE_NAME) A
)
WHERE RN BETWEEN 21 AND 40

对比这两种写法,绝大多数的情况下,第一个查询的效率比第二个高得多。


SELECT * FROM
(SELECTA.*, rownum r
FROM
-- 這裡的SQL可以改成你真正要執行的SQL
(SELECT* FROM Articles
ORDERBY PubTime DESC
) A
--
-- 用上面的SQL得回來的集合,使用rownum去比對,這樣rownum就會從這
個集合的第一筆資料開始往下計算,所以這邊是抓取前100筆
WHERErownum  90;



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn