简体   繁体   中英

sql two columns of one table reference same column in another table

I have these 2 tables

tbl_link

    pID | fID_a | fID_b | link_desc
     1  |  1    |  2    |  aa + bb

tbl_structure

    pID | desc
     1  |  a
     2  |  b

fID_a and fID_b are foreign keys to pID in tbl_structure fID_a doesn't allow NULL values while fID_b does

I am trying to retrieve the desc of structure 2 when querying for structure 1

my sql query at the moment looks like this

SELECT a.link_desc, tbl_structure.desc FROM tbl_strukture 
LEFT JOIN tbl_link as a ON tbl_structure.pID = a.fID_a 
LEFT JOIN tbl_link as b ON tbl_structure.pID = b.fID_b 
WHERE tbl_structure.pID = 1

but I only get the desc of the structure with pID 1!

Thanks for your help!

Are you looking for this?

SELECT l.link_desc, 
       s.[desc] description1,
       s2.[desc] description2
  FROM tbl_link l LEFT JOIN tbl_structure s 
    ON l.fID_a = s.pID LEFT JOIN tbl_structure s2 
    ON l.fID_b = s2.pID 
WHERE s.pID = 1

SQLFiddle (SQL Server)

SQLFiddle (MySql)

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