多个连接到一个表(TSQL)

时间:2018-01-27 00:36:09

标签: sql sql-server tsql join outer-join

我需要Employee表中的行在OwnerID字段和GMID字段中具有空值。

    Select ConceptName,
       c.FirstName + space(1) + c.LastName as OwnerName,
       d.FirstName + space(1) + d.LastName as GeneralManager
     FROM Store a 
        join Concept b on a.ConceptID = b.ConceptID
        join Employee c on a.OwnerID = c.EmployeeID
        join Employee d on a.GMID = d.EmployeeID

查询正在运行...但是商店表在OwnerID和GMID字段中具有空值。我还需要进行哪些更改才能恢复空行?

更新 这是更正的查询。

   Select ConceptName,
      c.FirstName + space(1) + c.LastName as OwnerName,
      d.FirstName + space(1) + d.LastName as GeneralManager  
   FROM Store a 
     join Concept b on a.ConceptID = b.ConceptID
     LEFT JOIN Employee c on a.OwnerID = c.EmployeeID
     LEFT JOIN Employee d on a.GMID = d.EmployeeID

https://docs.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql?view=sql-server-2017

1 个答案:

答案 0 :(得分:2)

使用left join代替join

  

LEFT JOIN关键字返回左表(table1)中的所有记录,以及右表(table2)中的匹配记录。如果没有匹配,则结果从右侧为NULL。

加入类型:查看更多here

enter image description here enter image description here enter image description here enter image description here