How to use multiple LEFT JOINs in SQL?

2020-05-15 08:36发布

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

    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?

4条回答
Summer. ? 凉城
2楼-- · 2020-05-15 08:55

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>
查看更多
▲ chillily
3楼-- · 2020-05-15 09:02

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

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.

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-05-15 09:04

The required SQL will be some like:-

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

Hope it helps.

查看更多
爷的心禁止访问
5楼-- · 2020-05-15 09:14

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
查看更多
登录 后发表回答