简体   繁体   English

具有空值的 SQL Server 连接表

[英]SQL Server join tables with null value

Suppose I have these tables in SQL Server:假设我在 SQL Server 中有这些表:

tbl_Applicants tbl_申请人

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

tbl_ApplicantType tbl_ApplicantType

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

tbl_Department tbl_部门

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

I want to join the table so that I can get the result below我想加入表格以便我可以得到下面的结果

This is my desired result:这是我想要的结果:

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

I have this select statement:我有这个选择语句:

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

This is the result I get right now:这是我现在得到的结果:

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

Any idea how to achieve the result I want where I get the null values included?知道如何在包含空值的地方实现我想要的结果吗?

Never use commas in the FROM clause.切勿FROM子句中使用逗号。 Alway use proper, explicit, standard , readable JOIN syntax.始终使用正确的、明确的、标准的、可读的JOIN语法。

If you want all applicants, then you want LEFT 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 ;

Also note the use of meaningful table aliases rather than arbitrary letters.还要注意使用有意义的表别名而不是任意字母。 That is also a best practice.这也是一种最佳做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM