联合查询在前面的例子中已经出现过,只不过没有细说。
先来个例子吧
DbSession.Default.From<Customers>() .InnerJoin<Orders>(Customers._.CustomerID == Orders._.CustomerID) .ToDataTable();
生成的sql
Text: SELECT * FROM [Customers] INNER JOIN [Orders] ON ([Customers].[CustomerID] = [Orders].[CustomerID])
是非常简单操作就完成了。
方法 | 联合查询(sql) |
InnerJoin | inner join |
LeftJoin | left join |
RightJoin | right join |
CrossJoin | cross join |
FullJoin | full join |
Union | union |
UnionAll | union all |
还是上例子清爽一些
DbSession.Default.From<Customers>() .LeftJoin<Orders>(Customers._.CustomerID == Orders._.CustomerID) .Where(Customers._.Country == "USA") .ToDataTable();
生成的sql
Text: SELECT * FROM [Customers] LEFT OUTER JOIN [Orders] ON ([Customers].[CustomerID] = [Orders].[CustomerID]) WHERE [Customers].[Country] = @e3c66f9aa65c498abfd76908621b567a Parameters: @e3c66f9aa65c498abfd76908621b567a[String] = USA
InnerJoin、LeftJoin、RightJoin、CrossJoin、FullJoin这个操作都是类似的。
三个表及以上关联例如
DbSession.Default.From<Customers>() .InnerJoin<Orders>(Customers._.CustomerID == Orders._.CustomerID) .InnerJoin<Order_Details>(Order_Details._.OrderID == Orders._.OrderID) .Where(Customers._.Country == "USA") .ToDataTable();
生成的sql:
Text: SELECT * FROM [Customers] INNER JOIN [Orders] ON ([Customers].[CustomerID] = [Orders].[CustomerID]) INNER JOIN [Order Details] ON ([Order Details].[OrderID] = [Orders].[OrderID]) WHERE [Customers].[Country] = @5901349776db425492724e16c3c03a7a Parameters: @5901349776db425492724e16c3c03a7a[String] = USA
关联查询一下变简单了吧。
下面讲union 和 union all
这两个是两个结果的合集,union会区分结果排除相同的,union all 则直接合并结果集合。
DbSession.Default.From<Customers>().Where(Customers._.Country == "USA") .UnionAll(DbSession.Default.From<Customers>().Where(Customers._.Country == "UK")) .ToList();
生成的sql如下
Text: SELECT * FROM (( SELECT * FROM [Customers] WHERE [Customers].[Country] = @f5b865bb20b64387b2c1be466c6d0980) UNION ALL ( SELECT * FROM [Customers] WHERE [Customers].[Country] = @b7de905de065418dab5820094c764e1b)) AS Customers Parameters: @f5b865bb20b64387b2c1be466c6d0980[String] = USA @b7de905de065418dab5820094c764e1b[String] = UK
写到这里的时候发现了一个bug,所以请大家重新下载新版本。
union 和 union all用法是一样的,就不再举例子了。
下一节将讲述排序和分组。