pro*_*oob 1 sql sql-server join
假设我在 SQL Server 中有这些表:
tbl_申请人
ID | name | typeid | depid
---+------+--------+-------
1 | Mark | 1 | NULL
2 | Ted | 2 | 1
Run Code Online (Sandbox Code Playgroud)
tbl_ApplicantType
ID | Type
---+----------
1 | Student
2 | Employee
Run Code Online (Sandbox Code Playgroud)
tbl_部门
ID | department_name
---+----------------
1 | Finance
2 | HR
Run Code Online (Sandbox Code Playgroud)
我想加入表格以便我可以得到下面的结果
这是我想要的结果:
Name | type | department
-----+----------+---------------
Mark | Student | NULL
Ted | Employee | HR
Run Code Online (Sandbox Code Playgroud)
我有这个选择语句:
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
Run Code Online (Sandbox Code Playgroud)
这是我现在得到的结果:
Name | type | department
-----+----------+------------
Ted | Employee | HR
Run Code Online (Sandbox Code Playgroud)
知道如何在包含空值的地方实现我想要的结果吗?
切勿在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 ;
Run Code Online (Sandbox Code Playgroud)
还要注意使用有意义的表别名而不是任意字母。这也是一种最佳做法。