LEFT JOIN and RIGHT JOIN tutorial in php
What is LEFT JOIN ? :
The LEFT JOIN returns all records from the left table (table 1) and the matched records from the right table (table 2).
LEFT JOIN Syntax :
SELECT columns FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
If we want to perform LEFT JOIN Operation on two table "personaltwo" and table "city" then we can use below shown sql query :
In "personaltwo" table, column "city" is FOREIGN KEY and In "city" table, column "cid" is PRIMARY KEY.
SELECT * FROM personaltwo LEFT JOIN city ON personaltwo.city = city.cid;
If we want to use alias for table name "personaltwo" and "city", then we can use below shown sql query :
SELECT * FROM personaltwo p LEFT JOIN city c ON p.city = c.id;
If we want to select some specific columns from tables "personaltwo" and "city" and also we can use alias name for tables "personaltwo" and "city", Here we have used alias name "p" for table "personatwo" and alias name "c" for table "city", then we can use below shown sql query :
SELECT p.id, p.name, p.percentage, p.age, p.gender, c.cityname FROM personaltwo p LEFT JOIN city c ON p.city = c.cid;
If we want to apply some specific condition with LEFT JOIN from tables "personaltwo" and "city", then we can use below shown sql query :
SELECT p.id, p.name, p.percentage, p.age, p.gender, c.cityname FROM personaltwo p LEFT JOIN city c ON p.city = c.cid WHERE gender = "M";
If we want to arrange records in Ascending order with LEFT JOIN from tables "personaltwo" and "city" then we can use below shown sql query :
SELECT p.id, p.name, p.percentage, p.age, p.gender, c.cityname FROM personaltwo p LEFT JOIN city c ON p.city = c.cid WHERE gender = "M" ORDER BY p.name;
What is RIGHT JOIN ?
The RIGHT JOIN returns all records from the right table (table 2) and the matched records from the left table (table 1).
RIGHT JOIN Syntax :
SELECT column_name FROM table1 RIGHT JOIN table2 ON table1.colmn_name = table2.column_name;
If we want to perform RIGHT JOIN Operation on two tables "personaltwo" and "city" then we can use below shown sql query :
In "personaltwo" table, column "city" is FOREIGN KEY and In "city" table, column "cid" is PRIMARY KEY.
SELECT * FROM personaltwo RIGHT JOIN city ON personaltwo.city = city.cid;
If we want to select some specific columns from tables "personaltwo" and "city" and also we can use alias name for tables "personaltwo" and "city", Here we have used alias name "p" for table "personatwo" and alias name "c" for table "city", then we can use below shown sql query :
SELECT p.id, p.name, p.percentage, p.age, p.gender, c.cityname FROM personaltwo p RIGHT JOIN city c ON p.city = c.cid;
Comments
Post a Comment