Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL LEFT JOIN 3 tables

Tags:

sql

join

mysql

I have 3 tables:

Persons (PersonID, Name, SS) Fears (FearID, Fear) Person_Fear (ID, PersonID, FearID)

Now I'd like to list every person with whatever fear is linked to them (can be multiple fears but can also be none). The persons table has to be shown even if a person doesn't have a fear linked to them.

I think I need to do a LEFT JOIN, but my code doesn't seem to work:

SELECT persons.name,         persons.ss,         fears.fear  FROM   persons         LEFT JOIN fears                ON person_fear.personid = person_fear.fearid  

What am I doing wrong here?

like image 206
Joe Avatar asked Apr 25 '13 18:04

Joe


People also ask

How do I join 3 tables in left join in SQL?

SELECT column names FROM table1 LEFT JOIN table2 ON table1. matching_column = table2. matching_column; Note: For example, if you have a left table with 10 rows, you are guaranteed to have at least 10 rows after applying join operation on two tables.

Can we use LEFT join for 3 tables?

Can you LEFT JOIN three tables in SQL? Yes, indeed! You can use multiple LEFT JOINs in one query if needed for your analysis.

Can we join 3 tables in mysql?

It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.


1 Answers

You are trying to join Person_Fear.PersonID onto Person_Fear.FearID - This doesn't really make sense. You probably want something like:

SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons LEFT JOIN Person_Fear     INNER JOIN Fears     ON Person_Fear.FearID = Fears.FearID ON Person_Fear.PersonID = Persons.PersonID 

This joins Persons onto Fears via the intermediate table Person_Fear. Because the join between Persons and Person_Fear is a LEFT JOIN, you will get all Persons records.

Alternatively:

SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons LEFT JOIN Person_Fear ON Person_Fear.PersonID = Persons.PersonID LEFT JOIN Fears ON Person_Fear.FearID = Fears.FearID 
like image 114
Ant P Avatar answered Sep 21 '22 17:09

Ant P