Jump to: navigation, search

PHP MySQL Query Use LEFT OUTER JOIN

From w3cyberlearnings

Contents

PHP MySQL LEFT OUTER JOIN

The LEFT OUTER JOIN is the join based on left table, and it displays null for the right table if the join condition is not true.

Insert Two Records to employee table

You need these two records for testing purpose.

INSERT INTO employee VALUES(null,'Jiji','c');
INSERT INTO employee VALUES(null,'Mama','d');

Syntax

SELECT
  em.id as employee_id,
  em.name,
  em.grade,
  sal.salary,
  sal.id as salary_id
FROM
  employee em
LEFT OUTER JOIN employee_salary sal
  ON em.id = sal.employee_id

Example 1

<?php

define('HOST', 'localhost');
define('USER', 'root');
define('PASS', 'yeething');
define('DBNAME', 'woowood');

$connection = mysql_connect(HOST, USER, PASS) 
		  or die("can not connect to the server!<br/>");


$rdb = mysql_select_db(DBNAME) 
       or die("The " . DBNAME . "database could not be selected");

$sel_query = "
SELECT
  em.id as employee_id,
  em.name,
  em.grade,
  sal.salary,
  sal.id as salary_id
FROM
  employee em
LEFT OUTER JOIN employee_salary sal
  ON em.id = sal.employee_id";

$result = mysql_query($sel_query, $connection) or die(mysql_error($connection));

echo '<table border="1">';
echo '<tr><th>employee id</th>
	<th>Name</th>
	<th>Grade</th>
	<th>salary</th>
	<th>salary id</th></tr>';

while ($row = mysql_fetch_assoc($result)) {
	echo '<tr>';
	foreach ($row as $value) {
		echo '<td>' . $value . '</td>';
	}
	echo "</tr>";
}
echo '</table>';

mysql_close($connection);
?> 

Output

Php mysql leftouterjoin 1.png

Related Links


  1. MySQL Connect
  2. Create Database
  3. Connect to Database
  4. Delete Database
  5. Create Table
  6. Insert Record
  7. Insert From Array
  8. Insert From File
  9. Update Record
  10. Query Single Record
  11. Query Multiple Records
  12. Query Uses LIMIT
  13. Query Uses ORDER BY
  14. Delete Table
  1. Create Two Tables for this section tutorial
  2. Query Uses AND Operator
  3. Query Uses OR Operator
  4. Query Uses INNER JOIN
  5. Query Uses LEFT OUTER JOIN
  6. Query Uses RIGHT OUTER JOIN
  7. Query with Subquery
  1. MySQL Aggregate Count
  2. MySQL Aggregate SUM
  3. MySQL Aggregate MAX
  4. MySQL Aggregate MIN
  5. MySQL Aggregate AVG
  6. MySQL Query Uses GROUP BY
  7. MySQL Query Uses Having
  1. PHP MySQL Create Date
  2. PHP MySQL Insert Date
  3. PHP MySQL Query Date
Navigation
Web
SQL
MISC
References