本节将讲述查询的排序(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();