How to use multiple LEFT JOINs in SQL?

SqlJoinLeft Join

Sql Problem Overview


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?

Sql Solutions


Solution 1 - Sql

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.

Solution 2 - Sql

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>


    

Solution 3 - Sql

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.

Solution 4 - Sql

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncuteView Question on Stackoverflow
Solution 1 - SqlbtillyView Answer on Stackoverflow
Solution 2 - SqlDaniel DiPaoloView Answer on Stackoverflow
Solution 3 - SqlKnowledge CravingView Answer on Stackoverflow
Solution 4 - SqlRichardTheKiwiView Answer on Stackoverflow