简体   繁体   中英

select data from 1st table and get the 2nd table's field for 2 columns in table 1

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

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
  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

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