[英]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.