Home Tutorial Java Jdbc Joining two table using Natural Left join

 
 

Joining two table using Natural Left join
Posted on: June 1, 2010 at 12:00 AM
In Natural Left join, both table are merge to each other according to common field, but the priority is given to the first table's field values

Join Table with Natural left join

In Natural Left join, both table are merge to each other according to common field, but the priority is given to the first table's field values  means a left outer join returns all the values from the left table and matched values from the right table (NULL in case of no matching join predicate).

In left join, every row of left table appears at least once in joined table, If no matching row from the "right" table exists, NULL will appear in columns from Right Table for those records that have no match in Left Table.

Query for Left Join

SELECT *FROM employee NATURAL LEFT JOIN Emp_sal

The two tables before Left join --

"employee" table

"emp_sal" table

natleftjoin.java

import java.sql.*;

public class natleftjoin{
  public static void main(String[] args) {
    System.out.println("NATURAL LEFT JOIN");
    Connection con = null;
    try{
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection("jdbc:mysql://192.168.10.13:3306/ankdb","root","root");
      try{
        Statement st = con.createStatement();
        ResultSet res = st.executeQuery("SELECT *FROM "+"employee"+" NATURAL LEFT JOIN "+"emp_sal");
                 //Natural Left Join two tables
        System.out.println("Emp_code" + "\t" + "Emp_name" + "\t" + "Emp_salary"+"\t"
 +"Emp_designation");
    while(res.next()){
    int code = res.getInt("Emp_code");
    String name = res.getString("Emp_name");
    String sal = res.getString("Emp_salary");
    String post = res.getString("Emp_designation");

    System.out.println(code + "\t\t" + name + "\t\t" + sal+"\t\t"+post);
    }
      }
      catch (SQLException s){
      System.out.println("SQL statement is not executed!");
      }
    }
    catch (Exception e){
      e.printStackTrace();
    }
  }
}

OUTPUT

Download Example's code

Related Tags for Joining two table using Natural Left join:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.