摘要:本文主要向大家介绍了SQLServer数据库之SQLServer分页,通过具体的内容向大家展现,希望对大家学习SQLServer数据库有所帮助。
本文主要向大家介绍了SQLServer数据库之SQLServer分页,通过具体的内容向大家展现,希望对大家学习SQLServer数据库有所帮助。
1、为什么要分页?
当显示数据的时候,我们不会一下子把所有的数据都显示出来,比如说表中有一万条数据,难道我们要把一万条数据都一次性的显示出来吗?!即便显示给用户了,用户也看不过来。因此,不论是从效率的角度还是从用户的观看的角度,只查询部分来给用户显示就可以了。这样速度又快,用户看起来也方便啦。这也就要求从很大的表中查询一小部分显示给用户就可以了,那么这一小部分的数据就是分页实现的。
2、分页的本质:从一个大数据中查询一小部分出来。
3、分页的前提:
要分页查询,或者分页显示之前,首先要确定按照什么排序,然后才能确定哪些记录应该在第一页,哪些记录应该在第二页。
4、分页的方法:top分页法和ROW_NUMBER()方法。
5、top分页法:
5.1、思想:首先要排序,然后要查哪一页的时候,就把哪一页之前的数据的ID查询出来,再从总数据中把这些ID排除掉,剩下的就是你没看过的,再把没看过的排个序,最后取前N个就可以了。
5.2、具体实施:
select top(pageSize) * from 表名 where 列名 not in(select top(pageSize*(pageIndex-1)) 列名 from 表名 order by 列名 asc)order by 列名;
如:select top (pageSize) * from Student where autoId not in( select top(pageSize*(pageIndex-1)) autoId from Student order by autoId asc) order by autoId;
6、使用row_number()实现分页:
6.1、top分页是老早之前的分页方法,效率并不是很高。SQLServer2005以后出现了row_number()分页方法。
6.2、分页思路:
先把现有的数据重新编号,然后根据用户要查看的每页记录条数,以及要查看第几页。确定应该查询第几条到第几条。
6.3、具体实施:
先排序,然后编号。
select *,Rn=row_number() over(order by CustomerId asc) from Customers;
最后实现:每页显示7条,要查看第8页。
select *
from(select *,Rn=row_number() over(order by CustomerId asc) from Customers) as t
where t.Rn between (8-1)*7+1 and 8*7;
select *
from (select Rn=row_number()over(order by autoId asc),* from Student)as s
where s.Rn between (3-1)*7+1 and 3*7;
select
tSName,tsAge,tClassName
from
TblStudent as ts inner join TblClass as tc on ts.tSClassId=tc.tClassId;
select
tSName,tsAge,tClassName
from
TblStudent as ts inner join TblClass as tc on ts.tSClassId=tc.tClassId
where ts.tSAge>20;
select
t1.tSName,t1.tsAge,t2.tClassName,t3.tScore
from
TblStudent as t1 inner join TblClass as t2 on t1.tSClassId=t2.tClassId
inner join TblScore as t3 on t1.tSId=t3.tsId;
总结:
当查询第一页的时候,用top方法,效率最高;
本文由职坐标整理并发布,希望对同学们学习SQL Server有所帮助,更多内容请关注职坐标数据库SQL Server数据库频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号