Home > Database > Mysql Tutorial > body text

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

WBOY
Release: 2016-06-01 13:25:10
Original
1046 people have browsed it

bitsCN.com 今天,老师带偶们复习了一下数据库中的分页,总体来说,今天感觉还不错,因为以前学的还没忘。好了,进入正题,
首先,说说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

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template