Use Natural Join in PHP

In this article I explain how to use natural join in PHP.
  • 2896

Introduction

When you want to "join"  two tables on the behalf of it's common column you can use equi join and in this process you specify on or using keyword to specifies those column, by which tables will be join. So Natural keyword or Natural join provide a facility to join tables without specifying column name. In short When you code a natural join, you do not specify the column that is used to join two tables. The database automatically joins that tables on the behalf of all columns in the two tables that have the same name. This type of join only work correctly on certain type of designed database.

Example of Natural Join in PHP

<?php

$con=mysql_connect("localhost","root","");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

mysql_select_db("mysql", $con);

 

 print "<h2>MySQL: Join with Natural keyword</h2>";

$result = mysql_query("select id,fname,salary,role from emp NATURAL JOIN designation");

echo "<table border='1'>

<tr>

<th>Empid</th>

<th>Firstname</th>

<th>Salary</th>

<th>Role</th>

</tr>";

while($row = mysql_fetch_array($result))

  {

   echo "<tr>";

   echo "<td>" . $row['id'] . "</td>";

   echo "<td>" . $row['fname'] . "</td>";

   echo "<td>" . $row['salary'] . "</td>";

   echo "<td>" . $row['role'] . "</td>";

  echo "</tr>";

  }

  echo "</table>"; 

 

   print "<h2>MySQL: Join with Natural keyword (other Example)</h2>";

$result = mysql_query("select id,fname,salary,role,hire_date from emp NATURAL JOIN designation LEFT JOIN joining USING(id)");

echo "<table border='1'>

<tr>

<th>Empid</th>

<th>Firstname</th>

<th>Salary</th>

<th>Role</th>

<th>JoiningDate</th>

</tr>";

while($row = mysql_fetch_array($result))

  {

   echo "<tr>";

   echo "<td>" . $row['id'] . "</td>";

   echo "<td>" . $row['fname'] . "</td>";

   echo "<td>" . $row['salary'] . "</td>";

   echo "<td>" . $row['role'] . "</td>";

    echo "<td>" . $row['hire_date'] . "</td>";

  echo "</tr>";

  }

  echo "</table>";

  mysql_close($con);

  ?>

 Output

use-natural-keyword-with-join-in-php.jpg

© 2019 DotNetHeaven. All rights reserved.