簡體   English   中英

具有空值的 SQL Server 連接表

[英]SQL Server join tables with null value

假設我在 SQL Server 中有這些表:

tbl_申請人

ID | name | typeid | depid
---+------+--------+-------
1  | Mark |  1     | NULL
2  | Ted  |  2     | 1

tbl_ApplicantType

ID | Type
---+----------
1  | Student
2  | Employee

tbl_部門

ID | department_name
---+----------------
1  | Finance
2  | HR

我想加入表格以便我可以得到下面的結果

這是我想要的結果:

Name |   type   | department
-----+----------+---------------
Mark | Student  | NULL
Ted  | Employee | HR

我有這個選擇語句:

select 
    a.name, b.type, c.department_name
from 
    tbl_applicants a, tbl_ApplicantType b, tbl_Department c
where 
    a.depid = c.ID and a.typeid = b.ID

這是我現在得到的結果:

Name |   type   | department
-----+----------+------------
Ted  | Employee | HR

知道如何在包含空值的地方實現我想要的結果嗎?

切勿FROM子句中使用逗號。 始終使用正確的、明確的、標准的、可讀的JOIN語法。

如果您想要所有申請人,那么您想要LEFT JOIN

select a.name, apt.type, d.department_name
from tbl_applicants a left join
     tbl_ApplicantType apt
     on a.tpeid = apt.id left join
     tbl_Department d
     on a.depid = d.ID ;

還要注意使用有意義的表別名而不是任意字母。 這也是一種最佳做法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM