SQL 3表sql连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6414602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:04:06  来源:igfitidea点击:

3 table sql join

sqljoin

提问by Sam

I need to join tableA, tableB, and tableC, but it's possible that tableB won't have a corresponding row. Posted below is how 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.

我需要连接 tableA、tableB 和 tableC,但 tableB 可能没有相应的行。下面发布的是我目前如何进行查询。它的问题在于,如果 tableB 没有相应的行,则不会返回结果。我的 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]

回答by MatBailie

Don't use the ,syntax. Use JOINto allow for a readable LEFT JOIN...

不要使用,语法。使用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

回答by Michael Fredrickson

Use a LEFT JOIN.

使用一个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

回答by Mark Sherretta

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.

如果 [more where conditions] 在 B 上,那么您需要将它们包含在 OUTER JOIN ON 子句中。

回答by Chris Cunningham

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 INNERor OUTERjoin on table c (do you want records returned if there are no matching rows in tableC)? Here is a link for the general issue.

此处的术语(以便您可以查找更多详细信息)是外部联接。其他答案很好——但是要注意您是否想要表 c 上的anINNEROUTERjoin (如果 tableC 中没有匹配的行,您是否希望返回记录)?这是一般问题的链接。

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

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