如何在SQL中使用多个LEFT JOIN?

65

在 SQL 查询中是否可以使用多个左连接?

    LEFT JOIN
        ab 
    ON
        ab.sht = cd.sht

我想添加另一个查询语句,像这样附加它? 会起作用吗?

    LEFT JOIN
        ab AND aa
    ON
        ab.sht = cd.sht
           AND
        aa.sht = cc.sht

这个会起作用吗?

4个回答

66

可以实现。每个连接表都需要一个“ON”。

LEFT JOIN ab
  ON ab.sht = cd.sht
LEFT JOIN aa
  ON aa.sht = cd.sht

顺便提一下,我个人对于复杂的SQL格式化的偏好在这篇博客中有描述:http://bentilly.blogspot.com/2011/02/sql-formatting-style.html。如果你要经常写这样的语句,那么这篇博客可能会有所帮助。


41

可以,但是语法与您所拥有的不同

SELECT
    <fields>
FROM
    <table1>
    LEFT JOIN <table2>
        ON <criteria for join>
        AND <other criteria for join>
    LEFT JOIN <table3> 
        ON <criteria for join>
        AND <other criteria for join>

感谢您展示了JOIN中的AND条件。我曾经错误地将一些搜索条件移动到WHERE子句中,让我很头疼! - Santosh
那个答案应该被选为最佳。 - mvxxx

15

所需的 SQL 将如下:

SELECT * FROM cd
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cd.sht
....

1

根据您的表格顺序,您有两个选择

create table aa (sht int)
create table cc (sht int)
create table cd (sht int)
create table ab (sht int)

-- type 1    
select * from cd
inner join cc on cd.sht = cc.sht
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cc.sht

-- type 2
select * from cc
inner join cc on cd.sht = cc.sht
LEFT JOIN ab
LEFT JOIN aa
ON aa.sht = ab.sht
ON ab.sht = cd.sht

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接