PHP Programing language

PHP MySQL Left Join
Previous Home Next

We are know in this previous lesson how to join two table , and this lesson we will read a Left join.

Declaration MySQL LEFT JOIN

The normal join and left join between more differences available:

The normal join is simply join for two table , but the left join syntax is quite different and somewhat more complex. Besides looking different, the LEFT JOIN gives extra consideration to the table that is on the left. "on the left" is being simply refers to the table that it's appearing before the LEFT JOIN in our SQL statement.

This extra consideration to the left table can be thought of as special kind of preservation. Each item in the left table will show up in a MySQL result, even if there isn't a match with the other table that it is being joined to.

Differences between MySQL Join and LEFT JOIN

Family Table

Position Age
Dad 45
Mom 41
Daughter 17

Food Table

Meal Position
Steak Dad
Salad Mom
Spinach Daughter
Tacos Dad

We executed a simple query that selected all meals that were liked by a family member with this simple join query:

Simplified MySQL Query:

SELECT food.Meal, family.Position 
FROM family, food 
WHERE food.Position = family.Position

Result Table:

Meal Position
Steak Dad
Salad Mom
Tacos Dad

In this queries all the member is listed then how can we decide to use a LEFT JOIN in the query instead, even if they do not have a favorite dish in our food table.This is because a left join will preserve the records of the "left" table.

Example of the MySQL LEFT JOIN

PHP and MySQL Code:


// Make a MySQL Connection
// Construct our join query

$query = "SELECT family.Position, food.Meal ".
"FROM family LEFT JOIN food ".
"ON family.Position = food.Position"; 

$result = mysql_query($query) or die(mysql_error());

// Print out the contents of each row into a table 

while($row = mysql_fetch_array($result))
echo $row['Position']. " - ". $row['Meal'];
echo "<br />";


Dad - Steak
Dad - Tacos
Mom - Salad
Daughter -
Dog -

Success! The LEFT JOIN preserved every family member, including those who don't yet have a favorite meal in the food table! Please feel free to play around with LEFT JOIN until you feel like you have a solid grasp of it. This stuff isn't easy.

Previous Home Next