LINQ to SQL语句(4)之Join
系列文章导航:
LINQ to SQL语句(2)之Select/Distinct
LINQ to SQL语句(3)之Count/Sum/Min/Max/Avg
LINQ to SQL语句(6)之Group By/Having
LINQ to SQL语句(7)之Exists/In/Any/All/Contains
LINQ to SQL语句(8)之Concat/Union/Intersect/Except
LINQ to SQL语句(9)之Top/Bottom和Paging和SqlMethods
LINQ to SQL语句(12)之Delete和使用Attach
LINQ to SQL语句(14)之Null语义和DateTime
LINQ to SQL语句(19)之ADO.NET与LINQ to SQL
GroupJoin
像上面所说的,没有join和into,被翻译成SelectMany,同时有join和into时,那么就被翻译为GroupJoin。在这里into的概念是对其结果进行重新命名。
1.双向联接(Two way join):
此示例显式联接两个表并从这两个表投影出结果:
var q = from c in db.Customers join o in db.Orders on c.CustomerID equals o.CustomerID into orders select new { c.ContactName, OrderCount = orders.Count() };
说明:在一对多关系中,左边是1,它每条记录为c(from c in db.Customers),右边是Many,其每条记录叫做o ( join o in db.Orders ),每对应左边的一个c,就会有一组o,那这一组o,就叫做orders,也就是说,我们把一组o命名为orders,这就是into用途。这也就是为什么在select语句中,orders可以调用聚合函数Count。在T-SQL中,使用其内嵌的T-SQL返回值作为字段值。如图所示:
生成SQL语句为:
SELECT [t0].[ContactName], ( SELECT COUNT(*) FROM [dbo].[Orders] AS [t1] WHERE [t0].[CustomerID] = [t1].[CustomerID] ) AS [OrderCount] FROM [dbo].[Customers] AS [t0]
2.三向联接(There way join):
此示例显式联接三个表并分别从每个表投影出结果:
var q = from c in db.Customers join o in db.Orders on c.CustomerID equals o.CustomerID into ords join e in db.Employees on c.City equals e.City into emps select new { c.ContactName, ords = ords.Count(), emps = emps.Count() };
生成SQL语句为:
SELECT [t0].[ContactName], ( SELECT COUNT(*) FROM [dbo].[Orders] AS [t1] WHERE [t0].[CustomerID] = [t1].[CustomerID] ) AS [ords], ( SELECT COUNT(*) FROM [dbo].[Employees] AS [t2] WHERE [t0].[City] = [t2].[City] ) AS [emps] FROM [dbo].[Customers] AS [t0]