程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> LINQ to SQL語句(4)之Join

LINQ to SQL語句(4)之Join

編輯:關於.NET

Join操作符

適用場景:在我們表關系中有一對一關系,一對多關系, 多對多關系等。對各個表之間的關系,就用這些實現對多個表的操作。

說明:在Join操作中,分別為Join(Join查詢), SelectMany(Select一對多選擇) 和GroupJoin(分組Join查詢)。

該擴展方法對兩個序列中鍵匹配的元素進 行inner join操作

SelectMany

說明:我們在寫查詢語句時,如果 被翻譯成SelectMany需要滿足2個條件。1:查詢語句中沒有join和into,2:必 須出現EntitySet。在我們表關系中有一對一關系,一對多關系,多對多關系等 ,下面分別介紹一下。

1.一對多關系(1 to Many):

var q =
  from c in db.Customers
  from o in c.Orders
   where c.City == "London"
  select o;

語句描述:Customers與Orders是一對多關系。即Orders在Customers類中以 EntitySet形式出現。所以第二個from是從c.Orders而不是db.Orders裡進行篩選 。這個例子在From子句中使用外鍵導航選擇倫敦客戶的所有訂單。

var q =
  from p in db.Products
  where p.Supplier.Country == "USA" && p.UnitsInStock == 0
  select p;

語句描述:這一句使用了 p.Supplier.Country條件,間接關聯了Supplier表。這個例子在Where子句中使 用外鍵導航篩選其供應商在美國且缺貨的產品。生成SQL語句為:

SELECT [t0].[ProductID], [t0].[ProductName], [t0]. [SupplierID],
[t0].[CategoryID],[t0].[QuantityPerUnit],[t0]. [UnitPrice],
[t0].[UnitsInStock], [t0].[UnitsOnOrder],[t0]. [ReorderLevel],
[t0].[Discontinued] FROM [dbo].[Products] AS [t0]
LEFT OUTER JOIN [dbo].[Suppliers] AS [t1] ON
[t1]. [SupplierID] = [t0].[SupplierID]
WHERE ([t1].[Country] = @p0) AND ([t0].[UnitsInStock] = @p1)
-- @p0: Input NVarChar (Size = 3; Prec = 0; Scale = 0) [USA]
-- @p1: Input Int (Size = 0; Prec = 0; Scale = 0) [0]

2.多對多關系(Many to Many):

var q =
  from e in db.Employees
  from et in e.EmployeeTerritories
  where e.City == "Seattle"
  select new
  {
    e.FirstName,
     e.LastName,
    et.Territory.TerritoryDescription
   };

說明:多對多關系一般會涉及三個表(如果有一個表是自關 聯的,那有可能只有2個表)。這一句語句涉及Employees, EmployeeTerritories, Territories三個表。它們的關系是1:M:1。Employees 和Territories沒有很明確的關系。

語句描述:這個例子在From子句中使 用外鍵導航篩選在西雅圖的雇員,同時列出其所在地區。這條生成SQL語句為:

SELECT [t0].[FirstName], [t0].[LastName], [t2]. [TerritoryDescription]
FROM [dbo].[Employees] AS [t0] CROSS JOIN [dbo].[EmployeeTerritories]
AS [t1] INNER JOIN [dbo]. [Territories] AS [t2] ON
[t2].[TerritoryID] = [t1].[TerritoryID]
WHERE ([t0].[City] = @p0) AND ([t1].[EmployeeID] = [t0]. [EmployeeID])
-- @p0: Input NVarChar (Size = 7; Prec = 0; Scale = 0) [Seattle]

3.自聯接關系:

var q =
  from e1 in db.Employees
  from e2 in e1.Employees
  where e1.City == e2.City
  select new {
    FirstName1 = e1.FirstName, LastName1 = e1.LastName,
    FirstName2 = e2.FirstName, LastName2 = e2.LastName,
    e1.City
   };

語句描述:這個例子在select 子句中使用外鍵導航篩選成 對的雇員,每對中一個雇員隸屬於另一個雇員,且兩個雇員都來自相同城市。生 成SQL語句為:

SELECT [t0].[FirstName] AS [FirstName1], [t0].[LastName] AS
[LastName1],[t1].[FirstName] AS [FirstName2], [t1].[LastName] AS
[LastName2],[t0].[City] FROM [dbo].[Employees] AS [t0],
[dbo].[Employees] AS [t1] WHERE ([t0].[City] = [t1]. [City]) AND
([t1].[ReportsTo] = [t0].[EmployeeID])
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]

3.左外部聯接(Left Outer Join):

此示例說明如何通過使用 此示例說明如何通過使用 DefaultIfEmpty() 獲取左外部聯接。在雇員沒有訂單時,DefaultIfEmpty()方 法返回null:

var q =
  from e in db.Employees
   join o in db.Orders on e equals o.Employee into ords
  from o in ords.DefaultIfEmpty()
  select new
  {
     e.FirstName,
    e.LastName,
    Order = o
   };

說明:以Employees左表,Orders右表,Orders 表中為空時, 用null值填充。Join的結果重命名ords,使用DefaultIfEmpty()函數對其再次查 詢。其最後的結果中有個Order,因為from o in ords.DefaultIfEmpty() 是對 ords組再一次遍歷,所以,最後結果中的Order並不是一個集合。但是,如果沒 有from o in ords.DefaultIfEmpty() 這句,最後的select語句寫成select new { e.FirstName, e.LastName, Order = ords }的話,那麼Order就是一個集合。

4.投影的Let賦值(Projected let assignment):

說明:let語句 是重命名。let位於第一個from和select語句之間。

這個例子從聯接投影 出最終“Let”表達式:

var q =
  from c in db.Customers
  join o in db.Orders on c.CustomerID
   equals o.CustomerID into ords
  let z = c.City + c.Country
  from o in ords
  select new
  {
     c.ContactName,
    o.OrderID,
    z
   };

5.組合鍵(Composite Key):

這個例子顯示帶有組合 鍵的聯接:

var q =
  from o in db.Orders
  from p in db.Products
  join d in db.OrderDetails
    on new
    {
      o.OrderID,
       p.ProductID
    } equals
      new
       {
        d.OrderID,
         d.ProductID
      }
    into details
  from d in details
  select new
  {
    o.OrderID,
    p.ProductID,
    d.UnitPrice
   };

說明:使用三個表,並且用匿名類來說明:使用三個表,並 且用匿名類來表示它們之間的關系。它們之間的關系不能用一個鍵描述清楚,所 以用匿名類,來表示組合鍵。還有一種是兩個表之間是用組合鍵表示關系的,不 需要使用匿名類。

6.可為null/不可為null的鍵關系 (Nullable/Nonnullable Key Relationship):

這個實例顯示如何構造一 側可為 null 而另一側不可為 null 的聯接:

var q =
   from o in db.Orders
  join e in db.Employees
    on o.EmployeeID equals
    (int?)e.EmployeeID into emps
   from e in emps
  select new
  {
     o.OrderID,
    e.FirstName
  };

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved