Showing posts with label Left Join. Show all posts
Showing posts with label Left Join. Show all posts

Tuesday 27 November 2012

MySQL LEFT JOIN

The LEFT JOIN keyword returns all rows from left table and returns match rows from right table.

family Table:

PositionAge
Dad41
Mom35
Daughter17
Dog12

food Table:

MealPosition
RiceDad
DosaMom
Idly
EggDog

When we decide to use a LEFT JOIN in the query instead, all the family members be listed, 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.
 
<?php 
/* Make a MySQL Connection */
$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 "
";
}
?>
Output:-
Dad - Dosa Mom - Rice Daughter - NULL Dog - Egg