sql分页

1:测试表

create database DBTest
use DBTest

--创建测试表
create table pagetest
(
id int identity(1,1) not null,
col01 int null,
col02 nvarchar(50) null,
col03 datetime null
)

--1万记录集
declare @i int
set @i=0
while(@i<10000)
begin
    insert into pagetest select cast(floor(rand()*10000) as int),left(newid(),10),getdate()
    set @i=@i+1
end

2.几种典型的分页sql,下面例子是每页50条,198*50=9900,取第199页数据。

--写法1,not in/top
select top 50 * from pagetest 
where id not in (select top 9900 id from pagetest order by id)
order by id




--写法2,not exists
select top 50 * from pagetest 
where not exists 
(select 1 from (select top 9900 id from pagetest order by id)a  where a.id=pagetest.id)
order by id

--写法3,max/top
select top 50 * from pagetest
where id>(select max(id) from (select top 9900 id from pagetest order by id)a)
order by id

--写法4,row_number()
select top 50 * from 
(select row_number()over(order by id)rownumber,* from pagetest)a
where rownumber>9900

select * from 
(select row_number()over(order by id)rownumber,* from pagetest)a
where rownumber>1and rownumber<9951

select * from 
(select row_number()over(order by id)rownumber,* from pagetest)a
where rownumber between 9901 and 9950

--写法5,在csdn上一帖子看到的,row_number() 变体,不基于已有字段产生记录序号,先按条件筛选以及排好序,再在结果集上给一常量列用于产生记录序号
select *
from (
    select row_number()over(order by tempColumn)rownumber,*
    from (select top 9950 tempColumn=0,* from pagetest where 1=1 order by id)a
)b
where rownumber>9900

 

 但是推荐这种写法(查询30条数据);原因是在使用以上过程中

row_number()over(order by id)rownumber,* from pagetest)方法过程中,查询的区间越大,耗时越长(比如查询10000到10030之间数据远比0到30之间时间长)
 select * from (select top (6960) row_number() over(order by 提货时间) as xx,* from View_Boss_Show ) as xx where xx> 6930

 

 

原帖在这里 http://www.cnblogs.com/songjianpin/articles/3489050.html
原帖在这里 http://www.cnblogs.com/songjianpin/articles/3489050.html

(此随笔仅为个人收藏,节选原帖部分。更加详情内容请见原帖)

 

posted @ 2017-10-15 16:33  楚景然  阅读(190)  评论(0编辑  收藏  举报