之前通过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

 

版权声明:本文为zhaorong0912原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zhaorong0912/p/9657377.html