Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Multiple LEFT JOIN, one-to-many

Tags:

sql

join

I am looking for a way to perform multiple joins from one source table to more than one table. Similar to the following:

SELECT a.NAME, b.address, c.phone
FROM tblname a
LEFT JOIN tbladdress b ON a.nid = b.nid

I also want to perform a left join on the Telephone table tblPhone at the same time:

tblname a left join tblPhone c on a.PID = c.PID

Try as I might I can't see how to put this into one query.

like image 528
oooo ooo Avatar asked Oct 07 '11 11:10

oooo ooo


People also ask

IS LEFT join 1 to many?

SQL LEFT JOIN examples Each location belongs to one and only one country while each country can have zero or more locations. The relationship between the countries and locations tables is one-to-many.

How do multiple Left JOINs work?

Here when it comes to Left Join in SQL it only returns all the records or tuples or rows from left table and only those records matching from the right table. Syntax For Left Join: SELECT column names FROM table1 LEFT JOIN table2 ON table1.

Can you do more than one left join?

Yes, indeed! You can use multiple LEFT JOINs in one query if needed for your analysis.

How do you optimize SQL query with multiple left JOINs?

Here's a better formulation without changing anything. It moves the LEFT JOINs into the SELECT part and avoids the GROUP BY . Show activity on this post. Note that in your SELECT clause you should either use values that are grouped by (or functionally dependent on them), or use some aggregation.


1 Answers

You can simply repeat your JOIN clauses as many times as is needed, e.g.:

SELECT a.NAME
    ,b.address
    ,c.phone
FROM tblname a
LEFT JOIN tbladdress b ON a.nid = b.nid
LEFT JOIN tblPhone c ON a.PID = c.PID
like image 110
D'Arcy Rittich Avatar answered Oct 01 '22 13:10

D'Arcy Rittich