SQL内部将多个表连接到类似键上的一个表

时间:2017-08-31 21:11:54

标签: sql-server inner-join

我正在开发一个项目,其中包含一个Employee表,其中包含EmployeeID(Int)键入的所有员工的所有名称

我还有一个Job表,其中包括JobName as string和Foreman,ProjectManager,Project Coordinator,AccountManager as INT,它们链接回Employee表。

我需要能够从员工表中提取分配给该工作的每个员工的名字和姓氏。我已经尝试过下面的查询,但没有产生任何结果。

我错过了什么......

SELECT
    j.jobsitename,
    j.jobsiteaddress, 
    CONCAT( RTRIM( e.empFirstName ), ' ', RTRIM( e.empLastName ) ) AS Foreman,
    CONCAT( RTRIM( pm.empFirstName ), ' ', RTRIM( pm.empLastName ) ) AS ProjectManager,
    CONCAT( RTRIM( pc.empFirstName ), ' ', RTRIM( pc.empLastName ) ) AS  ProjectCoordinator
FROM
    mpjob AS j 
    INNER JOIN mpEmployee AS e  ON j.jobforeman   = e.empemployeeid
    INNER JOIN mpEmployee AS pm ON j.jobProjMgr   = pm.empemployeeid
    INNER JOIN mpEmployee AS pc ON j.jobProjCoord = pc.empemployeeid

1 个答案:

答案 0 :(得分:0)

SELECT
   j.jobsitename,
   j.jobsiteaddress,
   e.empFirstName as ForemanFirstName,
   e.empLastName as ForemanLastName,
   pm.empFirstName as PmFirstName,
   pm.empLastName as PmLastName,
   pc.empFirstName as PcFirstName,
   pc.empLastName as PcLastName
FROM mpjob AS j
LEFT JOIN mpEmployee AS e ON j.jobforeman = e.empemployeeid
LEFT JOIN mpEmployee AS pm ON j.jobProjMgr = pm.empemployeeid
LEFT JOIN mpEmployee AS pc ON j.jobProjCoord = pc.empemployeeid

LEFT JOIN这些值。 如果有工头,PM和PC,INNER JOIN将返回这些值。 LEFT JOIN显示mpJob中的所有数据,即使没有。