mssqlserver优化分页2种方法详细比较
1,测试条件:
写一个JDBC链接数据库的方法,执行查询;
测试数据 1000 条;
采用存储过程procedure;
2,存储过程procedure:
------------------->
分页-1代码
create procedure pro_page
@pagecont int,
@pageon int
as
select top(@pagecont) id,zifu from test_1 where id not in (select top(@pagecont*@pageon) id from test_1);
go
exec pro_page 10,4;
@pagecont int,
@pageon int
as
select top(@pagecont) id,zifu from test_1 where id not in (select top(@pagecont*@pageon) id from test_1);
go
exec pro_page 10,4;
------------------------>
分页-2代码
create procedure pro_pages
@pagecont int,
@pageon int
as
select top(@pagecont) * from test_1
where (id > (select MAX(id) from (select top(@pagecont*@pageon) id from test_1 order by id) AS T)) order by ID
go
exec pro_pages 10,4;
@pagecont int,
@pageon int
as
select top(@pagecont) * from test_1
where (id > (select MAX(id) from (select top(@pagecont*@pageon) id from test_1 order by id) AS T)) order by ID
go
exec pro_pages 10,4;
3,测试结果:
分页-2经过测试无论显示第几页的数据效率都是一样在1-2s就显示出来。
分页-1经过测试当分页值越大就越慢,在得到第一页需要1-2s,如果显示第99页是大约1M才显示出来,如果数据更多瓶颈就更严重。
可以看出2种分页效率差距之大,但是很多人在分页时都用的方法-1。
4,纯sql语句分页:
A. select top(10) * from test_1 where id not in (select top(10*?) id from test_1);
B. select top(10) * from test_1 where (id > (select MAX(id) from (select top(10*?) id from test_1 order by id) AS T)) order by ID");
执行效率B>A, 当A分页数越大时效率就越差,B无论页数是多少效率都一样
注意:测试数据数量要足够多,100页以上。