之前通过row_number()实现分页查询时:
select top [PageSize] * from ( select row_number() over (order by id desc) as RowNum,* from table ) as A where RowNum > (PageIndex - 1) * PageSize
发现查询出来的结果顺序是不确定的,查询官方文档(地址:https://docs.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql?view=sql-server-2017)得到原因:
ROW_NUMBER()是非确定性函数,当如下条件满足时,结果集顺序是确定的:
1、分区列的值是唯一的。( PARTITION BY)
2、order by排序的值是唯一的。
3、分区列的值和order by排序的值的组合是唯一的。
固用between and 代替,查询出来的结果再次排序:
select * from ( select row_number() over (order by id desc) as RowNum,* from table ) as A where RowNum between (PageIndex - 1) * PageSize + 1 and PageIndex * PageSize order by RowNum asc