高性能SQL分页语句
第一种方法:效率最高
1
2
3
4
5
6
7
8
9
10
11
|
SELECT TOP 页大小 *
FROM
(
SELECT ROW_NUMBER() OVER ( ORDER BY id) AS RowNumber,* FROM table1
) as A
WHERE
RowNumber > 页大小*(页数-1)
--注解:首先利用Row_number()为table1表的每一行添加一个行号,给行号这一列取名'RowNumber' 在over()方法中将'RowNumber'做了升序排列
--然后将'RowNumber'列 与table1表的所有列 形成一个表A
--重点在where条件。假如当前页(currentPage)是第2页,每页显示10个数据(pageSzie)。那么第一页的数据就是第11-20条
--所以为了显示第二页的数据,即显示第11-20条数据,那么就让RowNumber大于 10*(2-1)
|
存储过程 (表名aa)
1
2
3
4
5
6
7
8
9
|
if(exists( select * from sys.procedures where name = 'p_location_paging' )) --如果p_location_paging这个存储过程存在
drop proc p_location_paging --那么就删除这个存储过程
go
create proc p_location_paging(@pageSize int , @currentPage int ) --创建存储过程,定义两个变量'每页显示的条数'和'当前页'
as
select top (@pageSize) * from (
select ROW_NUMBER() over( order by locid) as rowid ,* from aa
) as A where rowid> (@pageSize)*((@currentPage)-1)
|
第二种方法:效率次之
1
2
3
4
5
6
7
8
9
10
11
|
SELECT
TOP
页大小 *
--如果每页显示10条数据,那么这里就是查询10条数据
FROM
table1
WHERE
id >
--假如当前页为第三页,那么就需要查询21-30条数据,即:id>20
(
SELECT
ISNULL
(
MAX
(id),0)
--查询子查询中最大的id
FROM
(
SELECT
TOP
页大小*(当前页-1) id
FROM
table1
ORDER
BY
id
)
as
A
)
ORDER
BY
id
|
存储过程(表名 aa)
if(exists(
select
*
from
sys.procedures
where
name
=
'p_location_paging'
))
drop
proc p_location_paging
go
create
proc p_location_paging(@pageSize
int
,@currentPage
int
)
as
select
top
(@pageSize) *
from
aa
where
locId>(
select
ISNULL
(
MAX
(locId),0)
from
(
select
top
((@pageSize)*(@currentPage-1))locid
from
location
order
by
locId)
as
a
)
order
by
locId
第三种方法:效果最差
1
2
3
4
5
6
7
8
|
SELECT
TOP
页大小 *
FROM
table1
WHERE
id
NOT
IN
--where条件语句限定要查询的数据不是子查询里面包含的数据。即查询"子查询"后面的10条数据。即当前页的数据
(
--如果当前页是第二页,每页显示10条数据,那么这里就是获取当前页前面的所有数据。
SELECT
TOP
页大小*(当前页-1) id
FROM
table1
ORDER
BY
id
)
ORDER
BY
id
|