在SQL INNER JOIN中使用两列

时间:2013-11-21 11:46:21

标签: sql sql-server join inner-join

表A

AID     AName
1       Alpha
2       Bravo
3       Charlie

表B

BID     BName
1       Delta
2       Echo
3       Foxtrot

表C

CID     AID     BID
1       1       null
2       null    2
3       3       null

我正在使用以下SQL语句:

SELECT C.CID, A.Name AS First, B.Name AS Second FROM TableC 
INNER JOIN TableA ON TableC.AID = TableA.AID
INNER JOIN TableB ON TableC.BID = TableB.BID

但显示空白记录。预期结果应为:

CID     First     Second
1       Alpha
2                 Echo
3       Charlie

有什么建议吗?

3 个答案:

答案 0 :(得分:3)

使用LEFT JOIN代替INNER JOIN

答案 1 :(得分:1)

您想要的是FULL OUTER JOINUNION

更新: 再次查看表格后......对每个A,B表格使用LEFT JOIN

SELECT C.CID, A.AName, B.BName
FROM C
LEFT JOIN A ON C.AID = A.AID
LEFT JOIN B ON C.BID = B.BID

答案 2 :(得分:1)

SELECT C.CID,A.Name AS First,B.Name AS Second 来自TableC LEFT JOIN TableA ON TableC.AID = TableA.AID LEFT JOIN TableB ON TableC.BID = TableB.BID