sql两个列的一个表引用另一个表中的同一列

时间:2013-05-29 08:26:47

标签: sql foreign-keys left-join

我有这两个表

tbl_link

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

tbl_structure

    pID | desc
     1  |  a
     2  |  b

fID_a和fID_b是tbl_structure中pID的外键 当fID_b执行

时,fID_a不允许NULL值

我在查询结构1时尝试检索结构2的desc

我的SQL查询此刻看起来像这样

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

但我只得到pID 1的结构desc!

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

你在找这个吗?

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)