Reputation: 17
Well, I have two tables in an sql database. One has an ID column and its description.
Second table has two specific columns among many namely RefID1 and RefID2 so they both be having ID from the first table.
Now the problem is that I want to write a sql select statement from table 2 and display 1st table's description at the place of RefID1 and RefID2 instead of the numeric IDs.
Hope I was clear in explaining my question :)
I will be very thankful for your replies.
Regards,
Mujtaba Panjwani
Upvotes: 0
Views: 161
Reputation: 4129
select first.description , second.description from tableone
left join
(select a.id, a.description from tableone a inner join tabletwo b on a.id = b.RefID1)first
on first.id = tableone.id
left join
(select a.id, a.description from tableone a inner join tabletwo b on a.id = b.RefID2)second
on second.id = tableone.id
or
select a.description , b.description from tabletwo left join tableone a
on tabletwo.RefID1 = a.id left join tableone b
on tabletwo.RefID2 = b.id
Upvotes: 1
Reputation: 4999
This statement allows for the possibility of either RefID1 or RefID2 being null. It will return a null value for a.description or b.description if either respective RefID# is null. The only way to stop your query from returning the RefID1 and RefID2 is to explicitly list all fields you want returned from A (tabl1) instead of using A.*
SELECT A.*, B.description as description1, C.description as description2 FROM tabl1 A
LEFT JOIN tbl2 B on a.RefID1 = B.ID
LEFT JOIN tbl2 C on a.RefID2 = C.ID
Upvotes: 2