sql 两种分页offset和row_number简单分析

时间:2023-03-09 06:42:30
sql 两种分页offset和row_number简单分析

新建临时表字段id,向临时表里插入1,2,3,4,5,6

if object_id('tempdb..#test') is not null drop table #test
create table #test(id int)
insert into #test(id)values(1),(2),(3),(4),(5),(6)

declare @page int---当前页面
declare @rows int---页面大小
set @page=2
set @rows=3

---------当前页面为2,页面大小为3---则结果得到id(4,5,6)--------

(1)使用offset i rows fetch next j rows only 方式---i=(@page-1)*@rows,j=@rows
select t10.id from #test t10
order by t10.id--需要一个排序,否则分不了页
offset (@page-1)*@rows rows fetch next @rows rows only---offset的当前页面是从零开始

(2)使用row_number()函数得出新排序lineid,在用between 条件筛选页面

select t11.lineid,t11.id from (select cast(ROW_NUMBER() over (order by id asc) as int) lineid,id from #test) t11
where t11.lineid between (@page-1)*@rows+1 and @rows+(@page-1)*@rows+1
order by t11.line

结果如下:

sql 两种分页offset和row_number简单分析