本節將講述查詢的排序(order by) 和 分組(group by)。
先說排序
在分頁中如果沒有指定排序,組件會默認一個排序來實現分頁。
例如
DbSession.Default.From<Products>()
.Page(10, 2)
.Where(Products._.CategoryID.SelectIn(1, 2, 3))
.ToList();
生成的sql如下:
Text:
SELECT * FROM
( SELECT TOP 10 * FROM
( SELECT TOP 20 * FROM [Products]
WHERE [Products].[CategoryID]
IN (@c651c8c47b4f4b7587a65b1efeea17a2,@210f5286b2ec4ceabae99f4729d22a74,@5abe298074eb43e98016af330da896e1) ORDER BY [Products].[ProductID] ASC) AS tempIntable ORDER BY [ProductID] DESC) AS tempOuttable
ORDER BY [ProductID] ASC
Parameters:
@c651c8c47b4f4b7587a65b1efeea17a2[Int32] = 1 @210f5286b2ec4ceabae99f4729d22a74[Int32] = 2 @5abe298074eb43e98016af330da896e1[Int32] = 3
這裡就默認指定了productid作為排序。
當然我們也可自己指定排序,
DbSession.Default.From<Products>()
.Page(10, 2)
.Where(Products._.CategoryID.SelectIn(1, 2, 3))
.OrderBy(Products._.CategoryID.Asc)
.ToList();
生成的sql如下:
Text:
SELECT * FROM
( SELECT TOP 10 * FROM
( SELECT TOP 20 * FROM [Products]
WHERE [Products].[CategoryID] IN (@2ba49ec0bf2e47558a06a5ec8a80476a,@1963fb47beb9421896891620c89abddb,@80d632cbcd5843958606bf85371a0428)
ORDER BY [Products].[CategoryID] ASC) AS tempIntable
ORDER BY [CategoryID] DESC) AS tempOuttable
ORDER BY [CategoryID] ASC
Parameters:
@2ba49ec0bf2e47558a06a5ec8a80476a[Int32] = 1 @1963fb47beb9421896891620c89abddb[Int32] = 2 @80d632cbcd5843958606bf85371a0428[Int32] = 3
分頁的時候就按照categoryid來正序排列。
排序在查詢中設置的方法就是OrderBy( )
如果多個字段排序則如下操作:
DbSession.Default.From<Products>()
.OrderBy(Products._.CategoryID.Asc && Products._.ProductID.Asc)
.ToList();