解析數(shù)據(jù)庫分頁的兩種方法對比(row_number()over()和top的對比)
更新時間:2013年07月02日 10:02:47 作者:
本篇文章是對數(shù)據(jù)庫分頁的兩種方法對比(row_number()over()和top的對比)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
今天,老師帶偶們復(fù)習(xí)了一下數(shù)據(jù)庫中的分頁,總體來說,今天感覺還不錯,因為以前學(xué)的還沒忘。好了,進(jìn)入正題,
首先,說說top的方法
top方法其實就是將你要查的的頁數(shù)的數(shù)據(jù)前得數(shù)據(jù)去掉 再取前幾
例:
一頁3條數(shù)據(jù) 取第一頁的數(shù)據(jù)
-- 第一頁
select top 3 * from T_news;
取第五頁的數(shù)據(jù)
--第五頁
select top 3 * from T_News where id not in (select top (3*4) id from T_News) --關(guān)鍵就在于not in上 靠他來去掉前幾頁的數(shù)據(jù)
如果想要自己設(shè)定每頁幾條數(shù)據(jù)和看第幾頁的話也行 就多加個存儲過程
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()的方法
這個其實就是又給數(shù)據(jù)表加了一個列在用來確定數(shù)據(jù)是第幾條
例:
一頁3條數(shù)據(jù) 取第一頁的數(shù)據(jù)
select * from (select *,ROW_NUMBER()over(order by id asc) as number from T_News ) as tb1
where number between 1 and 3;
第五頁的數(shù)據(jù)
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;
自己設(shè)定每頁幾條數(shù)據(jù)和看第幾頁
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方法其實就是將你要查的的頁數(shù)的數(shù)據(jù)前得數(shù)據(jù)去掉 再取前幾
例:
復(fù)制代碼 代碼如下:
一頁3條數(shù)據(jù) 取第一頁的數(shù)據(jù)
-- 第一頁
select top 3 * from T_news;
取第五頁的數(shù)據(jù)
--第五頁
select top 3 * from T_News where id not in (select top (3*4) id from T_News) --關(guān)鍵就在于not in上 靠他來去掉前幾頁的數(shù)據(jù)
如果想要自己設(shè)定每頁幾條數(shù)據(jù)和看第幾頁的話也行 就多加個存儲過程
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()的方法
這個其實就是又給數(shù)據(jù)表加了一個列在用來確定數(shù)據(jù)是第幾條
例:
復(fù)制代碼 代碼如下:
一頁3條數(shù)據(jù) 取第一頁的數(shù)據(jù)
select * from (select *,ROW_NUMBER()over(order by id asc) as number from T_News ) as tb1
where number between 1 and 3;
第五頁的數(shù)據(jù)
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;
自己設(shè)定每頁幾條數(shù)據(jù)和看第幾頁
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
恩 就這樣 這是我的理解 希望能給看得人帶來幫助吧~
相關(guān)文章
MySQL5.7 group by新特性報錯1055的解決辦法
項目中本來使用的是mysql5.6進(jìn)行開發(fā),切換到5.7之后,突然發(fā)現(xiàn)原來的一些sql運行都報錯,錯誤編碼1055,錯誤信息和sql_mode中的“only_full_group_by“有關(guān)。下面小編給大家分享下解決辦法2016-12-12mysql中插入隨機(jī)字符串?dāng)?shù)據(jù)及常見問題說明
這篇文章主要介紹了mysql中插入隨機(jī)字符串?dāng)?shù)據(jù)及常見問題說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10MySQL性能優(yōu)化之table_cache配置參數(shù)淺析
這篇文章主要介紹了MySQL性能優(yōu)化之table_cache配置參數(shù)淺析,本文介紹了它的緩存機(jī)制、參數(shù)優(yōu)化及清空緩存的命令等,需要的朋友可以參考下2014-07-07