多个连接到同一个 table (TSQL)
Multiple joins into the same table (TSQL)
我需要来自 Employee table 的行,这些行在 OwnerID 字段和 GMID 字段中具有空值。
SELECT b.FirstName + space(1) + b.LastName AS OwnerName,
c.FirstName + space(1) + c.LastName AS GeneralManager
FROM Store a
JOIN Employee b ON a.OwnerID = b.EmployeeID
JOIN Employee c ON a.GMID = c.EmployeeID
查询正常...但是商店 table 在 OwnerID 和 GMID 字段中有空值。我还需要进行哪些更改才能恢复空行?
更新
这是更正后的查询。
SELECT b.FirstName + space(1) + b.LastName AS OwnerName,
c.FirstName + space(1) + c.LastName AS GeneralManager
FROM Store a
LEFT JOIN Employee b ON a.OwnerID = b.EmployeeID
LEFT JOIN Employee c ON a.GMID = c.EmployeeID
https://docs.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql?view=sql-server-2017
使用 left join
而不是 join
。
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side, if there is no match.
连接类型:查看更多here
我需要来自 Employee table 的行,这些行在 OwnerID 字段和 GMID 字段中具有空值。
SELECT b.FirstName + space(1) + b.LastName AS OwnerName,
c.FirstName + space(1) + c.LastName AS GeneralManager
FROM Store a
JOIN Employee b ON a.OwnerID = b.EmployeeID
JOIN Employee c ON a.GMID = c.EmployeeID
查询正常...但是商店 table 在 OwnerID 和 GMID 字段中有空值。我还需要进行哪些更改才能恢复空行?
更新 这是更正后的查询。
SELECT b.FirstName + space(1) + b.LastName AS OwnerName,
c.FirstName + space(1) + c.LastName AS GeneralManager
FROM Store a
LEFT JOIN Employee b ON a.OwnerID = b.EmployeeID
LEFT JOIN Employee c ON a.GMID = c.EmployeeID
https://docs.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql?view=sql-server-2017
使用 left join
而不是 join
。
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side, if there is no match.
连接类型:查看更多here