开发者

3 table sql join

I need to join tableA, tableB, and tableC, but it's possible that tableB won't have a corresponding row. Posted below is ho开发者_高级运维w I am currently doing the query. The problem with it is that if tableB doesn't have a correspoinding row, it won't return a result. My sql skills are very rusty so I appreciate your help. Thanks.

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]


Don't use the , syntax. Use JOIN to allow for a readable 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


Use a 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


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]

If the [more where conditions] are on B, then you need to include them in the OUTER JOIN ON clause.


The terminology here (so you can look up more details) is an Outer Join. The other answer(s) are fine -- but watch out for whether you want an INNER or OUTER join on table c (do you want records returned if there are no matching rows in tableC)? Here is a link for the general issue.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜