UNION and UNION ALL in PHP

 In "personal" table, there are 6 columns named id, name, percentage, age, gender, city.

In "personal" table, column name "id" is PRIMARY KEY and column name "city" is FOREIGN KEY.


In "courses" table, there are 2 columns named course_id and course_name.

In "courses" table, column name "course_id" is PRIMARY KEY.


In "city" table, there are 2 columns named cid and cityname.

In "city" table, column name "cid" is PRIMARY KEY.


In "lecturers" table, there are 6 columns named id, name, percentage, age, gender, id_of_personal.

In "lecturers" table, column name "id" is PRIMARY KEY and column name "id_of_personal" is FOREIGN KEY.


UNION and UNION ALL Syntax :

SELECT column1, column2 FROM table1 UNION/UNION ALL SELECT column1, column2 FROM table2;


RULES :

1) Each SELECT statement within UNION must have the same number of columns.

2) The columns must also have similar data types.

3) The columns in each SELECT statement must also be in the same order.


If we want to UNION both tables named "personal" and "lecturers" then we can use  below shown sql query :

SELECT * FROM personal UNION SELECT * FROM lecturers;

Using above query, when we perform above query then duplicate entries will also appear because we have selected all columns using "*" Operator in (SELECT * FROM).

If we want to remove duplicate "name"  entries in both columns then we have to specify column name as shown below sql query :

SELECT name FROM personal UNION SELECT name FROM lecturers;


If we want to specify any condition in above query then we can use below shown sql query :

SELECT name, age, gender FROM personal WHERE gender = "F" UNION ALL SELECT name, age, gender FROM lecturers WHERE gender = "M";


If we want to select any particular record based on any specific condition then we can use below shown sql query :

SELECT name, age FROM personal WHERE city = (SELECT cid FROM city WHERE cityname = "Delhi") UNION ALL SELECT name, age FROM lecturers WHERE id_of_personal = (SELECT cid FROM city WHERE cityname = "Delhi") ;


If we want to select any particular record from multiple tables using UNION ALL then we can use below shown sql query :

SELECT p.name, p.age, c.cityname FROM personal p INNER JOIN city c ON p.city = c.cid WHERE c.cityname = "Delhi" UNION ALL SELECT l.name, l.age, ci.cityname FROM lecturers l INNER JOIN city ci ON l.id_of_personal = ci.cid WHERE ci.cityname = "Delhi";

Comments

Popular posts from this blog

GROUP BY Clause and HAVING Clause in PHP

Method Overriding in Traits in PHP

Mysqli database Connection and Display Table Data from Database