繁体   English   中英

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

[英]sql two columns of one table reference same column in another table

我有这两张桌子

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_a不允许NULL值,而fID_b执行

我在查询结构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!

谢谢你的帮助!

你在找这个吗?

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM