如何外连接同一个表

时间:2016-01-19 08:10:00

标签: sql-server join

enter image description here

我有两个表,即tbl_Certificates和tbl_Employees。 并且由员工批准和认证证书。在某些情况下,preparedBy和approvdby属性可能为NULL,但我仍然想要所有证书列表。 预期结果如上图所示。 我知道这是一个非常基本的问题。 在此先感谢... :)

2 个答案:

答案 0 :(得分:3)

SELECT * FROM tbl_Certificates AS Certs
    LEFT JOIN tbl_Employees AS PreparedBy ON Certs.PrepareById=PreparedBy.Id
    LEFT JOIN tbl_Employees AS ApprovedBy ON Certs.ApprovedById=ApprovedBy.Id

答案 1 :(得分:0)

要简短:你就这么做了

select
    cert.id                 as "CertificateId"
    ,preparedBy.Name        as "PreparedBy"
    ,preparedBy.Designation as "Prepared By Designation"
    ,approvedBy.Name        as "ApprovedBy"
    ,approvedBy.Designation as "Approved By Designation"
from
    tbl_Certificates cert
    left outer join tbl_Employees preparedBy
        on preparedBy.id = cert.PreparedById
    left outer join tbl_Employees approvedBy
        on preparedBy.id = cert.ApprovedById