>데이터 베이스 >MySQL 튜토리얼 >Oracle row_number() 高效分页

Oracle row_number() 高效分页

WBOY
WBOY원래의
2016-06-07 17:45:591237검색

利用自带的函数分页当然会高效一些了,本文章介绍一篇关于Oracle row_number() 高效分页方法,有需要的朋友参考一下。

利用自带的函数分页当然会高效一些了,本文章介绍一篇关于Oracle row_number() 高效分页方法,有需要的朋友参考一下。

第一步:我先用rownum

 代码如下 复制代码

-- row_number,不是rownum
--根据n_count从大到小排列,每页3条
SELECT ROWNUM r,t.* FROM t_news t
WHERE ROWNUM ORDER BY t.n_count DESC
--问题:为什么order by以后,行号是乱的?
SELECT ROWNUM r,t.* FROM t_news t
--原因:先分配了行号,再根据n_count排序

--所以必须排序,再生成行号
SELECT ROWNUM r,t.* FROM (
SELECT t.* FROM t_news t ORDER BY t.n_count DESC ) t

--分页
--err
SELECT ROWNUM r,t.* FROM (
SELECT t.* FROM t_news t ORDER BY t.n_count DESC ) t
WHERE r between 1 AND 3

--第1页
SELECT ROWNUM r,t.* FROM (
SELECT t.* FROM t_news t ORDER BY t.n_count DESC ) t
WHERE ROWNUM between 1 AND 3

--第2页
SELECT ROWNUM r,t.* FROM (
SELECT t.* FROM t_news t ORDER BY t.n_count DESC ) t
WHERE ROWNUM between 4 AND 6
--error: ROWNUM必须从1开始!
SELECT k.* FROM (
SELECT ROWNUM r,t.* FROM (
SELECT t.* FROM t_news t ORDER BY t.n_count DESC ) t
) k
WHERE r BETWEEN 4 AND 6

--麻烦,效率低!


*****第二步:我用row_number() over()函数

 代码如下 复制代码

t2.* from
(select t.*,row_number()over(order by t.n_count desc) orderNumber from t_news t order by t.n_count desc)t2 where orderNumber between 1and 3;


*****************************************************************************************************************************************88
SELECT * FROM (
SELECT t.*,row_number() over(ORDER BY n_count DESC) r
FROM t_news t
ORDER BY t.n_count DESC
) t
WHERE r BETWEEN 4 AND 6

--通用语法: 解析函数() over(partition by 字段 order by 字段)

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.