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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4950296/
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 09:16:12  来源:igfitidea点击:

How to use multiple LEFT JOINs in SQL?

sqljoinleft-join

提问by cute

Is it possible to use multiple left joins in sql query?

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

    LEFT JOIN
        ab 
    ON
        ab.sht = cd.sht

i want to add to attach one more query like this to it? will it work?

我想添加一个这样的查询吗?它会起作用吗?

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

Will this work?

这会起作用吗?

回答by btilly

Yes it is possible. You need one ON for each join table.

对的,这是可能的。每个连接表都需要一个 ON。

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

Incidentally my personal formatting preference for complex SQL is described in http://bentilly.blogspot.com/2011/02/sql-formatting-style.html. If you're going to be writing a lot of this, it likely will help.

顺便提一下,我个人对复杂 SQL 的格式偏好在http://bentilly.blogspot.com/2011/02/sql-formatting-style.html 中有所描述。如果你要写很多这样的东西,它可能会有所帮助。

回答by Daniel DiPaolo

Yes, but the syntax is different than what you have

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

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>

回答by Knowledge Craving

The required SQL will be some like:-

所需的 SQL 将类似于:-

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

Hope it helps.

希望能帮助到你。

回答by RichardTheKiwi

You have two choices, depending on your table order

您有两种选择,具体取决于您的餐桌顺序

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