解析資料庫分頁的兩種方法對比(row_number()over()和top的對比)

來源:互聯網
上載者:User

今天,老師帶偶們複習了一下資料庫中的分頁,總體來說,今天感覺還不錯,因為以前學的還沒忘。好了,進入正題,
首先,說說top的方法
top方法其實就是將你要查的的頁數的資料前得資料去掉 再取前幾
例:
複製代碼 代碼如下: 一頁3條資料 取第一頁的資料
-- 第一頁
       select top 3 * from T_news;
                       取第五頁的資料
--第五頁
       select  top 3 * from T_News where id not in (select top (3*4) id from T_News)      --關鍵就在於not  in上 靠他來去掉前幾頁的資料
                    如果想要自己設定每頁幾條資料和看第幾頁的話也行 就多加個預存程序
create proc usp_fenye @geshu int,@yeshu int
as
 begin
   select top (@geshu) * from T_News where id not in (select top (@geshu*(@yeshu-1)) id from T_News)
 end

然後,我們再說說ROW_NUMBER()over()的方法
這個其實就是又給資料表加了一個列在用來確定資料是第幾條
例:
複製代碼 代碼如下:                       一頁3條資料 取第一頁的資料
   select * from (select *,ROW_NUMBER()over(order by id asc) as number from T_News ) as tb1
     where number between 1 and 3;
第五頁的資料
 select * from (select *,ROW_NUMBER()over(order by id asc) as number from T_News ) as tb1
     where number between 3*4+1 and 3*5;
                       自己設定每頁幾條資料和看第幾頁
create proc usp_fenye @geshu int,@yeshu int
 as
   begin
     select * from (select *,ROW_NUMBER()over(order by id asc) as number from T_News ) as tb1
     where number between  @geshu*(@yeshu-1)+1 and @geshu*@yeshu;
   end

恩 就這樣 這是我的理解 希望能給看得人帶來協助吧~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.