Introduction to MySQL Self Join
MySQL Self JOIN is an SQL statement that is used to intersect or join a table in the database to itself. Basically, a JOIN function combines two or more tables in SQL, but here Self Join is a regular Join that allows to combine records within a table based on a certain conditional expression. This type of joining of records with other records in the same table when a condition is matched is also called as a Unary relationship. Specially, here the Foreign key that exists in the table refers to the tables own Primary Key.
This means that a table row will join with every other row under a condition and this process is queried by a Self-Join SQL command. This Self Join in MySQL is a special kind of Join that is useful to query the hierarchical data and comparing records in the rows within a table. In the SQL statement query, we use Inner Join or Left Join Clauses with the Self Join to return a result set using any condition that satisfies. This is because it is difficult to refer more than one query for the same table. So, we have to use a different table alias to add a different name for the table when we use Self Join in MySQL otherwise the query displays an error when executed.
Following is the basic syntax of Self Join query in MySQL:
SELECT A.Column_Name, B.Column_Name,….FROM TableA T1, TableA T2 WHERE A.Common_Field = B.Common_Field;
Here, T1 and T2 are two aliases used for the same table named Table A in the database and the WHERE clause denotes any given conditional expression.
How MySQL Self Join works?
- In MySQL, Self-Join is important to query ordered data by comparing rows in the same table. The SQL query for Self-Join is applied in a table to itself showing as if there are two tables where using temporary names as alias for the same table in SQL statement.
- Therefore, the main application of this query in MySQL is when we have a table reference data rows in itself. Suppose, we have a table named Employee and there is a Supervisor_ID column that refers to the employee which is the head of the current employees in any particular company.
- Thus, there is a requirement of any relationship between the rows data that is stored in the table to apply the Self Join in MySQL within the same table.
- Let us consider a table named Persons with columns (PersonID, Name, Contact, Address, City).
- Suppose, we want to match persons that are from the same city in the table then, we use the following SQL Statement for Self-Join command in MySQL:
SELECT A.Name AS Name1, B.Name AS Name2, A.City FROM Persons A, Persons B WHERE A.PersonID <> B.PersonID AND A.City = B.City ORDER BY A.City;
Examples of MySQL Self Join
Given below are the examples of MySQL self Join: Let us consider a table named Persons.
Example #1 – MySQL Self Join using Inner Join Clause.
- Let us create a table Persons and insert some data as a sample to execute the query on them using Self Join in MYSQL with the following SQL commands:
CREATE TABLE Persons (PersonID int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), ReportsTo int, Title varchar(255));
Now, let us fetch the whole organization structure details. We are joining the Person table with itself based on the PersonID and ReportsTo column from the table which determines the job title with employees.
SELECT CONCAT (a.LastName, ', ', a.FirstName) AS Manager, CONCAT(b.LastName, ', ', b.FirstName) AS 'Direct Reporting' FROM persons b INNER JOIN persons a ON a.PersonID = b.ReportsTo ORDER BY Manager;
The result set will define the table of Persons with two different roles: ‘Manager’ and ‘Direct Reporting’ and only those employees who have a manager. However, the ‘Marketing’ is not displayed because the name is filtered out by the Inner Join clause as Reports to column is NULL with no value to match the condition applied.
Example #2 – MySQL Self Join using Left Join Clause.
Since the Marketing titled person has no Manager and is not included in the above result set but in the Left Join, we can display it even if it has no value for Manager.
SELECT IFNULL (CONCAT (a.LastName, ', ', a.FirstName), 'Top Manager') AS 'Manager', CONCAT(b.LastName, ', ', b.FirstName) AS 'Direct report' FROM Persons b LEFT JOIN Persons a ON a.PersonID = b.ReportsTo ORDER BY Manager DESC;
Here, the Marketing person is provided with ‘Top Manager’ as ‘Manager’ as its value for Reports To was NULL.
Example #3 – Use MySQL Self Join for comparing successive rows.
- For example, let us use Self Join in MySQL to fetch the rows by comparing the records within the same table.
- Let us consider another table named ‘Customer_Data’ with fields (ID, name, Age, Address, Salary) for this SQL query:
The SQL statement is as follows:
SELECT k.ID, l.Name, k.Salary FROM customer_data k, customer_data l WHERE k.Salary < l.Salary;
Example #4 – Use MySQL Self Join with Inner Join for comparing successive rows.
We have taken the ‘Customers’ table with fields (CustomerID, Name, CustomerNum, Payment_purpose, Amount, City) as an example or sample table to run the query using Self Join and comparing the rows in the table.
Here, the list of persons from Customers table is fetched who are located in the same city by joining the table to itself and using comparing operators like <,> and = for City column.
SELECT c1.city, c1.Name, c2.Name FROM customers c1 INNER JOIN customers c2 ON c1.city = c2.city AND c1.Name > c2.Name ORDER BY c1.city;
You can see there the result table a city column and two Name columns which contain different names of customers residing in the same place or city using the Join conditions where:
- city = c2.city ensures that both customers have the same city.
- Name > c2.Name ORDER BY c1.city checks that no same name of customers are included in the result rows.
Thus, likewise, we can apply it to fetch results from the same table under certain joining predicates and using Inner or Left Joins as well as comparison operators to query correct data from the table in the database.
Hence, we can say that a Self-Join in MySQL takes a ‘Selfie’ to itself but producing results considering the table as two using an alias so that the table name is not repeated twice which may produce an error. This type of regular join is useful for modeling an organized structure data form from a table and also allows comparing the rows and does needful to produce the required result.
This is a guide to MySQL Self Join. Here we discuss the introduction, examples and how MySQL Self Join works with proper code and output? You may also have a look at the following articles to learn more –