简体   繁体   中英

SQL Server join tables with null value

Suppose I have these tables in SQL Server:

tbl_Applicants

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

tbl_ApplicantType

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

tbl_Department

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. Alway use proper, explicit, standard , readable JOIN syntax.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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