Ms-Access-2010

協助部分加入

  • August 1, 2016

我是一名大學生,我正在使用的數據庫純粹是虛構的,但其中一部分需要我進行一個連接查詢。

我有 3 個表,每個表都有部分數據,但還需要使用其中兩個表作為基於主表的條件。我的意思是我有一個employee tableorder table並且customer table他們兩個唯一的共同點是員工或客戶的 ID 是訂單表的一部分。現在我要做的是創建一個連接語句,它將從員工和客戶表中獲取某些資訊,並且只有那些員工和客戶也在訂單表中的同一行上。

我應該如何製作這種類型的條件語句?任何使用相同基本場景的範例都可以使用,我可以使用它來幫助我建構自己的查詢。

這就是我現在所擁有的:

SELECT [Customer/Vendor_Info_local].Name_of_customer,
      [Customer/Vendor_Info_local].[Customer/VendorID],
      Employee_Info_local.Employee_Name, 
      Employee_Info_local.EmployeeID
FROM Employee_Info_local 
RIGHT JOIN ([Customer/Vendor_Info_local] 
RIGHT JOIN Order_Information_local 
  ON [Customer/Vendor_Info_local].[Customer/VendorID] = Order_Information_local.[Cusrtomer/VendorID]) 
  ON Employee_Info_local.EmployeeID = Order_Information_local.EmployeeID;
SELECT C.Name_of_customer,
      C.[Customer/VendorID],
      E.Employee_Name, 
      E.EmployeeID 
from Order_Information_local as O
JOIN Employee_Info_local as E
JOIN [Customer/Vendor_Info_local] as C
      ON C.[Customer/VendorID] = O.[Cusrtomer/VendorID]) 
     AND E.EmployeeID = O.EmployeeID;

只有員工和客戶都在訂單表中的同一行

這轉化為內部聯接而不是外部聯接:

SELECT cust.Name_of_customer,
      cust.[Customer/VendorID],
      emp.Employee_Name, 
      emp.EmployeeID
FROM Employee_Info_local AS emp
JOIN Order_Information_local AS ord
 ON emp.EmployeeID = ord.EmployeeID
JOIN [Customer/Vendor_Info_local] AS cust
 ON cust.[Customer/VendorID] = ord.[Cusrtomer/VendorID]

兩個建議:

  1. 使用表別名
  2. 更好地加入使用table JOIN table ON ... JOIN next table ON ...而不是table JOIN table JOIN next table ON ... ON .... 大多數人更喜歡這個,因為它更容易遵循/擴展(後者在最後一個條件下加入第一個表)。

引用自:https://dba.stackexchange.com/questions/145491