MSSQL两个内部联接到同一个表

时间:2017-11-11 12:20:41

标签: sql-server

我有一张表列出了一堆时间表(TK.DETAIL)。

在该表中,它引用了员工ID,我可以成功地使用该ID来从员工表中提取名字和姓氏(EMMain)

TK.DETAIL表还显示了项目ID,我可以通过INNER加入项目表(PR)来获取该项目的主管ID。

我要做的是加入PR和EMMain表以获取主管的名字和姓氏。

我当前的查询为我提供了员工ID的相同名字和姓氏。

我做错了什么。

   SELECT        tkDetail.Employee, tkDetail.WBS1, tkDetail.WBS2, tkDetail.LineItemApprovalStatus, tkDetail.LineItemApprover, PR.Supervisor, EMMain.LastName, EMMain.FirstName,EMMain.FirstName AS SupervisorFirst, EMMain.LastName AS supervisorlast
FROM            tkDetail INNER JOIN
                         PR ON tkDetail.WBS1 = PR.WBS1 INNER JOIN
                         EMMain ON tkDetail.Employee = EMMain.Employee INNER JOIN
                         EMMain AS EMPL ON PR.Supervisor = EMMain.Employee

WHERE (LineItemApprovalStatus is NULL)

3 个答案:

答案 0 :(得分:1)

请查看左连接是否有帮助并注意在第三次加入时您应该使用EMPL别名而不是表名再次

     SELECT tkDetail.Employee, tkDetail.WBS1, tkDetail.WBS2, 
     tkDetail.LineItemApprovalStatus, tkDetail.LineItemApprover, 
     PR.Supervisor, EMMain.LastName, EMMain.FirstName,SUP.FirstName AS 
      SupervisorFirst, SUP.LastName AS supervisorlast 
FROM tkDetail 
INNER JOIN PR ON tkDetail.WBS1 = PR.WBS1 
left JOIN EMMain ON tkDetail.Employee = EMMain.Employee 
left JOIN EMMain SUP ON PR.Supervisor = SUP.Employee WHERE (LineItemApprovalStatus is NULL) 

答案 1 :(得分:0)

没有数据很难说,但尝试这样做

SELECT *
FROM tkDetail 
INNER JOIN PR ON tkDetail.WBS1 = PR.WBS1 
INNER JOIN EMMain PR.Supervisor = EMMain.Employee
WHERE (LineItemApprovalStatus is NULL)

答案 2 :(得分:0)

也许它会像那样工作:

    SELECT tkDetail.Employee, tkDetail.WBS1, tkDetail.WBS2, tkDetail.LineItemApprovalStatus, tkDetail.LineItemApprover, PR.Supervisor, EMMain.LastName, EMMain.FirstName,EMMain.FirstName AS SupervisorFirst, EMMain.LastName AS supervisorlast
    FROM tkDetail INNER JOIN
     EMMain ON tkDetail.Employee = EMMain.Employee INNER JOIN 
     PR ON tkDetail.WBS1 = PR.WBS1 AND EMMain.Employee = PR.Supervisor  
    WHERE (LineItemApprovalStatus is NULL)