我已经在stackoverflow中检查了几个线程,但找不到我想要的答案。
我有3个表,第三个是链接表。
Table1: | Table2: | LinkTable:
ID Value | ID Value1 Value2 | Table1_ID Table2_ID
a aa | p pp ppp | a p
b bb | q qq qqq | b r
c bb | r rr rrr |
我使用了查询:
SELECT t1.Value t1Value, t2.Value1 t2Value1, t2.Value2 t2Value2
FROM Table1 t1
INNER JOIN LinkTable lt ON lt.Table1_ID = t1.ID
INNER JOIN Table2 t2 ON t2.ID = lt.Table2_ID
返回一个表:
t1Value t2Value1 t2Value2
aa pp ppp
bb rr rrr
我要找的结果是:
Result:
t1Value t2Value1 t2Value2
aa pp ppp
bb rr rrr
cc NULL NULL <=i.e. if the Table1 ID is not linked to Table2 ID the values should be null (or white-space)
如何在SQL中完成?
感谢。
PS:我现在正在做的是,我正在使用2个不同的查询(一个在上面提到,另一个用于空值),但我正在寻找一个查询。答案 0 :(得分:3)
您想要left outer join
:
SELECT t1.Value t1Value, t2.Value1 t2Value1, t2.Value2 t2Value2
FROM Table1 t1
LEFT JOIN LinkTable lt ON lt.Table1_ID = t1.ID
LEFT JOIN Table2 t2 ON t2.ID = lt.Table2_ID;