Oracle row_number() over()解析函數高效實現分頁

來源:互聯網
上載者:User

複製代碼 代碼如下:create table T_NEWS
(
ID NUMBER,
N_TYPE VARCHAR2(20),
N_TITLE VARCHAR2(30),
N_COUNT NUMBER
)

prompt Disabling triggers for T_NEWS...
alter table T_NEWS disable all triggers;
prompt Loading T_NEWS...
insert into T_NEWS (ID, N_TYPE, N_TITLE, N_COUNT)
values (1, 'IT', '愛it1', 100);
insert into T_NEWS (ID, N_TYPE, N_TITLE, N_COUNT)
values (2, '體育', '愛體育1', 10);
insert into T_NEWS (ID, N_TYPE, N_TITLE, N_COUNT)
values (3, '體育', '愛體育2', 30);
insert into T_NEWS (ID, N_TYPE, N_TITLE, N_COUNT)
values (4, 'IT', '愛it2', 300);
insert into T_NEWS (ID, N_TYPE, N_TITLE, N_COUNT)
values (5, 'IT', '愛it3', 200);
insert into T_NEWS (ID, N_TYPE, N_TITLE, N_COUNT)
values (6, '體育', '愛體育3', 20);
insert into T_NEWS (ID, N_TYPE, N_TITLE, N_COUNT)
values (7, '體育', '愛體育4', 60);
commit;

第一步:我先用rownum

--分頁 row_number,不是rownum
--根據n_count從大到小排列,每頁3條
SELECT ROWNUM r,t.* FROM t_news t
WHERE ROWNUM<=3
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()函數
select 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 欄位)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.