2013-04-23 31 views
2

我想從我的表Jobs中返回幾行,而且還要從表JobProducts(其中每個JobProduct都有到期日期)的下一個截止日期。SQL交叉連接錯誤無法綁定多部分標識

我有以下至今

SELECT J.CustomerID, J.JobID, J.Status, 
J.Deleted, J.JobNo, Customers.CompanyName AS [Company], 
J.DateCreated AS [Date Created], derivedtbl_1.DueDate AS [Due Date] 
FROM Jobs J 
LEFT OUTER JOIN 
Customers ON J.CustomerID = Customers.CustomerID CROSS JOIN 
(SELECT TOP (1) DueDate, JobProductID, JobID, ProductID, DepartmentID 
FROM  JobProducts AS JobProducts_1 
WHERE JobProducts_1.JobID = J.JobID 
ORDER BY DueDate) 
AS derivedtbl_1 

,但我得到的錯誤 多部分標識符「J.JobID」無法綁定。

任何幫助將不勝感激

回答

5

該錯誤似乎來自SQL Server。我認爲你是在混淆CROSS JOIN(至極是笛卡爾乘積)與CROSS APPLY

SELECT J.CustomerID, 
     J.JobID, 
     J.Status, 
     J.Deleted, 
     J.JobNo, 
     Customers.CompanyName AS [Company], 
     J.DateCreated AS [Date Created], 
     derivedtbl_1.DueDate AS [Due Date] 
FROM Jobs J 
LEFT JOIN Customers 
    ON J.CustomerID = Customers.CustomerID 
CROSS APPLY (SELECT TOP (1) DueDate, 
          JobProductID, 
          JobID, 
          ProductID, 
          DepartmentID 
      FROM JobProducts AS JobProducts_1 
      WHERE JobProducts_1.JobID = J.JobID 
      ORDER BY DueDate) 
AS derivedtbl_1 
0

你可以嘗試改變交叉聯接交叉應用

CROSS APPLY 
(SELECT TOP (1) DueDate, JobProductID, JobID, ProductID, DepartmentID 
FROM  JobProducts AS JobProducts_1 
WHERE JobProducts_1.JobID = J.JobID 
ORDER BY DueDate) 
相關問題