假设我们有两个表:
表TA
AID BID1 BID2
-- ---- ----
01 01 02
02 01 03
03 02 01
表TB
BID Name
--- ----
01 FOO
02 BOO
03 LOO
如果我想退回以下内容:
AID Name1
-- -----
01 FOO
02 FOO
03 BOO
我写了以下内容:
SELECT TA.AID, TB.Name as Name1
FROM TB
INNER JOIN TA on TB.BID = TA.BID1
但是,我无法弄清楚如何返回对应于BID1和BID2的TB.Name。更具体地说,我想返回以下内容:
AID Name1 Name2
-- ----- -----
01 FOO BOO
02 FOO LOO
03 BOO FOO
答案 0 :(得分:7)
您可以多次加入:
SELECT TA.AID, tb1.Name AS Name1, tb2.Name AS Name2
FROM TA
LEFT JOIN TB tb1
ON TA.BID1 = tb1.BID
LEFT JOIN TB tb2
ON TA.BID2 = tb2.BID;
注意:LEFT OUTER JOIN
将确保您始终从TA
获取所有记录,即使没有匹配。
的 LiveDemo
答案 1 :(得分:4)
再使用一次加入
SELECT TA.AID, TB.Name as Name1, T1.Name as Name2
FROM TB
INNER JOIN TA on TB.BID=TA.BID1
INNER JOIN TB T1 on T1.BID=TA.BID2;
答案 2 :(得分:3)
- 使用交叉申请的另一种方式
select ta.aid,a1.*,a2.*
from table1 ta
cross apply(select tb.name from tableb tb where tb.aid=ta.bid1) a1
cross apply(select tb.name from tableb tb where tb.aid=ta.bid2) a2