解析數據庫分頁的兩種方法對比(row_number()over()和top的對比)
更新時間:2013年07月02日 10:02:47 作者:
本篇文章是對數據庫分頁的兩種方法對比(row_number()over()和top的對比)進行了詳細的分析介紹,需要的朋友參考下
今天,老師帶偶們復習了一下數據庫中的分頁,總體來說,今天感覺還不錯,因為以前學的還沒忘。好了,進入正題,
首先,說說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
恩 就這樣 這是我的理解 希望能給看得人帶來幫助吧~
首先,說說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
恩 就這樣 這是我的理解 希望能給看得人帶來幫助吧~
相關文章
MySQL5.7 group by新特性報錯1055的解決辦法
項目中本來使用的是mysql5.6進行開發(fā),切換到5.7之后,突然發(fā)現原來的一些sql運行都報錯,錯誤編碼1055,錯誤信息和sql_mode中的“only_full_group_by“有關。下面小編給大家分享下解決辦法2016-12-12
MySQL性能優(yōu)化之table_cache配置參數淺析
這篇文章主要介紹了MySQL性能優(yōu)化之table_cache配置參數淺析,本文介紹了它的緩存機制、參數優(yōu)化及清空緩存的命令等,需要的朋友可以參考下2014-07-07

