2011-06-20 179 views
0

我需要連接tableA,tableB和tableC,但有可能tableB不會有對應的行。下面發佈是我目前正在做這個查詢。問題在於如果tableB沒有相應的行,它將不會返回結果。我的SQL技能非常生疏,所以我感謝你的幫助。謝謝。3表sql連接

SELECT [column names] 
FROM tableA AS a, tableB AS b, tableC as c 
WHERE b.blah = a.blah 
AND c.foo = a.foo 
AND [more where conditions] 
+0

您正在使用哪種RDBMS? – geoffspear

回答

2

使用LEFT JOIN

SELECT [column names] 
FROM 
    tableA AS a 
    LEFT JOIN tableB AS b ON b.blah = a.blah 
    JOIN tableC as c ON c.foo = a.foo 
4

請勿使用,語法。使用JOIN以允許可讀LEFT JOIN ...

SELECT 
    * 
FROM 
    tableA 
LEFT JOIN 
    tableB 
    ON TableB.x = TableA.y 
LEFT JOIN 
    tableC 
    ON TableC.x = TableB.y 
    AND TableC.y = TableA.z 
0
SELECT [column names] 
FROM tableA AS a INNER JOIN tableC as c ON (c.foo = a.foo) 
LEFT OUTER JOIN tableB as B on (b.blah = a.blah) 
WHERE [more where conditions] 

如果[更多那裏的條件]是在B,那麼你需要將它們包括在OUTER JOIN ON子句。

-1

這裏的術語(所以你可以查看更多的細節)是一個外部的加入。其他答案沒有問題 - 但要注意是否要在表c上加入INNEROUTER(如果tableC中沒有匹配的行,是否希望返回記錄)?這是一般問題的鏈接。

http://www.w3schools.com/sql/sql_join_left.asp