Reputation: 31
I am battling with joins and inner joins.
I have 2 tables that look like this:
USERS
-----------------------------------------
ID | fname | lname | div_1_id | div_2_id
-----------------------------------------
1 paul smith 1 2
2 john lip 2 null
3 kim long 1 4
DIVISIONS
------------------
ID | name
------------------
1 estate
2 litigation
3 property
4 civil
DESIRED RESULT (sql query)
--------------------------------------------------
user.ID | fname | lname | div_1_name | div_2_name
--------------------------------------------------
1 paul smith estate litigation
2 john lip litigation
3 kim long estate civil
I would like to create a new table from a MS sql query that looks like the above.
Upvotes: 0
Views: 85
Reputation: 18649
Try using sub-query:
select a.ID, a.fname, a.lname,
(select name from DIVISIONS b where b.id=a.div_1_id) div_1_name,
(select name from DIVISIONS b where b.id=a.div_2_id) div_2_name
from
USERS a
Upvotes: 1
Reputation: 3442
Use LEFT JOIN
for this:
SELECT u.ID, u.fname, u.lname
, d1.name as div_1_name
, d2.name as div_2_name
FROM USERS u
LEFT JOIN DIVISIONS d1 ON u.div_1_id = d1.ID
LEFT JOIN DIVISIONS d2 ON u.div_2_id = d2.ID
Upvotes: 1
Reputation: 8664
Use INNER JOIN
SELECT Users.ID, Users.fname, Users.lname, Divisions.name,Div.name
FROM Users INNER JOIN Divisions ON Users.div_id_1 = Divisions.ID
INNER JOIN Divisions Div ON Users.div_id_1 = Div.ID -- Second join with Divisions Table with Alias.
Upvotes: 0