服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|

服务器之家 - 数据库 - Mysql - 解析数据库分页的两种方法对比(row_number()over()和top的对比)

解析数据库分页的两种方法对比(row_number()over()和top的对比)

2020-01-05 16:36MYSQL教程网 Mysql

本篇文章是对数据库分页的两种方法对比(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


恩 就这样 这是我的理解 希望能给看得人带来帮助吧~

延伸 · 阅读

精彩推荐