几种常见SQL分页方式效率比较
1.创建测试环境,(插入100万条数据大概耗时5分钟)。
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条,19850=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,