Text: SELECT * FROM ( SELECT TOP 6 * FROM ( SELECT TOP 8 * FROM [Products] ORDER BY [Products].[ProductID] ASC) AS tempIntable ORDER BY [ProductID] DESC) AS tempOuttable ORDER BY [ProductID] ASC
page方法: DbSession.Default.From<Products>() .Page(10, 2) .ToList();查询每页10条的第2页数据,sql语句如下: Text: SELECT * FROM ( SELECT TOP 10 * FROM ( SELECT TOP 20 * FROM [Products] ORDER BY [Products].[ProductID] ASC) AS tempIntable ORDER BY [ProductID] DESC) AS tempOuttable ORDER BY [ProductID] ASC
当然在很多情况下我们是需要设置哪些列排序的。 例如: DbSession.Default.From<Products>() .Page(10, 2) .OrderBy(Products._.UnitPrice.Desc) .Where(Products._.CategoryID == 2) .ToList();查询条件是categoryid等于2,按照unitprice倒叙排序,每页10条的第2页数据。 生成的sql如下: Text: SELECT * FROM ( SELECT TOP 2 * FROM [Products] WHERE [Products].[CategoryID] = @bee7551993404c8592f07f9b01710bb5 ORDER BY [Products].[UnitPrice] ASC) AS temp_table ORDER BY [UnitPrice] DESC Parameters: @bee7551993404c8592f07f9b01710bb5[Int32] = 2 这样的sql语句是不是出乎意料啊,原来符合条件的查询第二页只有2条数据,所以查询的时候就直接unitprice正序top 2就完结了。
我们把条件去掉再看看: DbSession.Default.From<Products>() .Page(10, 2) .OrderBy(Products._.UnitPrice.Desc) //.Where(Products._.CategoryID == 2) .ToList();生成的sql如下: Text: SELECT * FROM ( SELECT TOP 10 * FROM ( SELECT TOP 20 * FROM [Products] ORDER BY [Products].[UnitPrice] DESC) AS tempIntable ORDER BY [UnitPrice] ASC) AS tempOuttable ORDER BY [UnitPrice] DESC 这样算是正常的生成格式了。
下面来sql server2005例子: DbSession.Default.From<Products>() .Page(10, 2) .OrderBy(Products._.UnitPrice.Desc) //.Where(Products._.CategoryID == 2) .ToList();代码还是上面的例子的,生成的sql: Text: SELECT * FROM ( SELECT *,row_number() over( ORDER BY [Products].[UnitPrice] DESC) AS tmp__rowid FROM [Products] ) AS tmp_table WHERE (tmp__rowid BETWEEN 11 AND 20) 方法的调用还是一样的,所以如果from的参数startIndex等于1,还是优先使用top,并没有使用row_numer()。