2011-02-09 152 views
34

是否有可能在SQL查询中使用多个左连接? 如果不是那么最新的解决方案?使用多个左连接

LEFT JOIN 
     ab 
    ON 
     ab.sht = cd.sht 

我想添加到atach这样给它多了一个查询? 它会工作吗?

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

Wil这项工作?

回答

40

是的,这是可能的。每个连接表需要一个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描述。如果你要写很多这个,它可能会有所帮助。

+0

你是什么意思?你可以在代码/查询说明? – cute 2011-02-09 20:54:12

+0

我已经添加了一个小代码示例。 – btilly 2011-02-09 20:57:07

17

是的,但语法比你有什么

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> 
+0

感谢您在JOIN上显示AND标准。我错误地将一些搜索条件移到WHERE子句中,这让我感到头疼! – Santosh 2015-03-12 11:22:16

8

不同所需的SQL会出现一些像: -

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

希望它能帮助。

+1

以这种格式查看LEFT JOIN,一个接一个地看待事物。 – 2017-06-16 13:53:29

0

你有两个选择,这取决于您的表顺序上

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