Reputation: 55
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?
Upvotes: 1
Views: 74
Reputation: 1269463
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.
Upvotes: 6