分页SQL

  1. Top(最慢,not in 数据庞大,而且不走索引,但支持性好,基本sql都支持)

    select top (@pagesize) * from Customers where CustomerID not in 
    (select top ((@pageindex - 1)* @pagesize) CustomerID from Customers order by CustomerID DESC) order by CustomerID DESC
    
  2. Row_Number(Sql2004以上才可以用效率挺好)

    select * from 
    (select ROW_NUMBER() OVER(order by CustomerID desc) as px,* from Customers) as a
    where a.px between ((@pageindex - 1)* @pagesize + 1) and (@pageindex*@pagesize)
    
  3. Offset Fetch (性能最高,sql2012才支持)

    select * from Customers order by CustomerID desc
    offset ((@pageindex - 1) * @pagesize) rows
    fetch next @pagesize rows only  
    
分页页码越大对分页效率影响就越大。top的分页方法早早出局,很明显是因为not in 的数据量太庞大了。row_number的分页方法算是比较好的了,而且sql2005及以上的数据库都可以用,受众范围比较大,而offset fecth的性能更加优越,但是只有sql2012及以上的才支持。