几种分页sql写法测试

左手的ㄟ右手 2021-12-05 03:35 356阅读 0赞

1.创建测试环境,(插入100万条数据大概耗时5分钟)。

  1. create database DBTest
  2. use DBTest
  3. --创建测试表
  4. create table pagetest
  5. (
  6. id int identity(1,1) not null,
  7. col01 int null,
  8. col02 nvarchar(50) null,
  9. col03 datetime null
  10. )
  11. --1万记录集
  12. declare @i int
  13. set @i=0
  14. while(@i<10000)
  15. begin
  16. insert into pagetest select cast(floor(rand()*10000) as int),left(newid(),10),getdate()
  17. set @i=@i+1
  18. end

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

  1. --写法1not in/top
  2. select top 50 * from pagetest
  3. where id not in (select top 9900 id from pagetest order by id)
  4. order by id
  5. --写法2not exists
  6. select top 50 * from pagetest
  7. where not exists
  8. (select 1 from (select top 9900 id from pagetest order by id)a where a.id=pagetest.id)
  9. order by id
  10. --写法3max/top
  11. select top 50 * from pagetest
  12. where id>(select max(id) from (select top 9900 id from pagetest order by id)a)
  13. order by id
  14. --写法4row_number()
  15. select top 50 * from
  16. (select row_number()over(order by id)rownumber,* from pagetest)a
  17. where rownumber>9900
  18. select * from
  19. (select row_number()over(order by id)rownumber,* from pagetest)a
  20. where rownumber>9900 and rownumber<9951
  21. select * from
  22. (select row_number()over(order by id)rownumber,* from pagetest)a
  23. where rownumber between 9901 and 9950
  24. --写法5,在csdn上一帖子看到的,row_number() 变体,不基于已有字段产生记录序号,先按条件筛选以及排好序,再在结果集上给一常量列用于产生记录序号
  25. select *
  26. from (
  27. select row_number()over(order by tempColumn)rownumber,*
  28. from (select top 9950 tempColumn=0,* from pagetest where 1=1 order by id)a
  29. )b
  30. where rownumber>9900

3.分别在1万,10万(取1990页),100(取19900页)记录集下测试。

  1. declare @begin_date datetime
  2. declare @end_date datetime
  3. select @begin_date = getdate()
  4. <.....YOUR CODE.....>
  5. select @end_date = getdate()
  6. select datediff(ms,@begin_date,@end_date) as '毫秒'

1万:基本感觉不到差异。
10万:
在这里插入图片描述
4.结论:

1.max/top,ROW_NUMBER()都是比较不错的分页方法。相比ROW_NUMBER()只支持sql2005及以上版本,max/top有更好的可移植性,能同时适用于sql2000,access。

2.not exists感觉是要比not in效率高一点点。

3.ROW_NUMBER()的3种不同写法效率看起来差不多。

4.ROW_NUMBER() 的变体基于我这个测试效率实在不好。

发表评论

表情:
评论列表 (有 0 条评论,356人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SQL SERVER 方式。

    背景: 在日常工作中,经常需要解决分页的问题,这也是真分页必须要做的一件事情。经常查询,发现有很多的分页方法,为了了解他们的分页效率我做了一个实验。当然,跟自己的服务器性