SQL JOIN未正确过滤

时间:2015-12-31 17:20:15

标签: sql sql-server-2008

我的SQL语句正确显示数据,直到我添加了最后两个JOIN语句。我需要以某种方式正确地#34;链接"他们对数据。

我的陈述:

FROM dbo.DailyWork AS dw
LEFT JOIN dbo.Labor as lab
ON dw.DailyWorkID=LAB.DailyWorkID
LEFT JOIN dbo.Company AS com
ON dw.CompanyID=com.CompanyID
LEFT JOIN dbo.Projects AS proj
ON dw.ProjectID=proj.ProjectID
JOIN dbo.LU_Trade AS trade
ON lab.TradeID=lab.TradeID
JOIN dbo.LU_Classification as class
ON lab.ClassID=class.ClassID

相关表格

Dailywork

SELECT [DailyWorkID]
      ,[Date]
      ,[CompanyID]
      ,[CrewID]
      ,[WorkDescription]
      ,[LastModified]
      ,[LastModifiedBy]
      ,[ProjectID]
      ,[GUID]
      ,[IsClosed]
      ,[TypeID]
      ,[CategoryID]
      ,[Status]
      ,[IsFromCrewSight]
  FROM [dbo].[DailyWork]

劳动

SELECT [LaborID]
      ,[DailyWorkID]
      ,[EmployeeID]
      ,[StartTime]
      ,[BreakTime]
      ,[FinishTime]
      ,[STQty]
      ,[OTQty]
      ,[DTQty]
      ,[TotalSTQty]
      ,[TotalOTQty]
      ,[TotalDTQty]
      ,[CostCodeReference]
      ,[Notes]
      ,[TradeID]
      ,[ClassID]
      ,[ManpowerQty]
      ,[UOM]
      ,[TotalManQtyPerCrew]
      ,[TotalManQtyPerCompany]
      ,[TotalManpowerQty]
      ,[SortOrder]
      ,[LastModified]
      ,[LastModifiedBy]
      ,[ProjectID]
      ,[GUID]
      ,[IsFromCrewSight]
  FROM [dbo].[Labor]

LU_Trade

SELECT [TradeID]
      ,[Description]
      ,[UserText1]
      ,[UserNum1]
      ,[SortOrder]
  FROM [dbo].[LU_Trade]

LU_Classification

SELECT [ClassID]
      ,[Description]
      ,[UserText1]
      ,[UserNum1]
      ,[SortOrder]
  FROM [dbo].[LU_Classification]

我的第一个想法是我应该使用dbo.Labor作为我的FROM语句,因为它结合了大多数列。但是,我仍然不知道如何联系"贸易和分类的逻辑。

2 个答案:

答案 0 :(得分:2)

这与您加入的内容有关。最初你有工作左加入DailyWork。左连接的本质是仅返回附加数据并保持DailyWork的行与Labor表中的任何内容都不匹配。

当您添加最后两个表时,您使用的JOIN等同于INNER JOIN。当查询尝试加入由Labor表的NULL生成的LEFT JOIN值时,这些行就会退出。

如果您更改原始查询中的最后两个联接以使用下面的LEFT JOIN,则应获得正确的行。

FROM dbo.DailyWork AS dw
LEFT JOIN dbo.Labor as lab
ON dw.DailyWorkID=LAB.DailyWorkID
LEFT JOIN dbo.Company AS com
ON dw.CompanyID=com.CompanyID
LEFT JOIN dbo.Projects AS proj
ON lab.ProjectID=proj.ProjectID
LEFT JOIN dbo.LU_Trade AS trade
ON lab.TradeID=trade.TradeID
LEFT JOIN dbo.LU_Classification as class
ON lab.ClassID=class.ClassID

另外,如果您的前两个表是可互换的,那么您是否需要对所有后续表使用左连接?

答案 1 :(得分:1)

我重写了基于Labor表的JOIN语句。它似乎修复了它。

FROM dbo.Labor as lab
LEFT JOIN dbo.DailyWork AS dw
ON lab.DailyWorkID=dw.DailyWorkID
LEFT JOIN dbo.Company AS com
ON dw.CompanyID=com.CompanyID
LEFT JOIN dbo.Projects AS proj
ON lab.ProjectID=proj.ProjectID
JOIN dbo.LU_Trade AS trade
ON lab.TradeID=trade.TradeID
JOIN dbo.LU_Classification as class
ON lab.ClassID=class.ClassID

现在我很好奇,是组合来自不同表格的信息的唯一方法,就是有一个表来结合所有列?