MySQL Self Join
Summary: in this tutorial, you will learn how to use MySQL self join that joins a table to itself using the inner join or left join.
In the previous tutorials, you have learned how to join a table to the other tables using INNER JOIN , LEFT JOIN , RIGHT JOIN , or CROSS JOIN clause. However, there is a special case that you need to join a table to itself, which is known as a self join.
The self join is often used to query hierarchical data or to compare a row with other rows within the same table.
To perform a self join, you must use table aliases to not repeat the same table name twice in a single query. Note that referencing a table twice or more in a query without using table aliases will cause an error.
MySQL self join examples
Let’s take a look at the employees table in the sample database.

The table employees stores not only employees data but also the organization structure data. The reportsto column is used to determine the manager id of an employee.
1) MySQL self join using INNER JOIN clause
To get the whole organization structure, you can join the employees table to itself using the employeeNumber and reportsTo columns. The table employees has two roles: one is the Manager and the other is Direct Reports.

The output only shows the employees who have a manager. However, you don’t see the President because his name is filtered out due to the INNER JOIN clause.
2) MySQL self join using LEFT JOIN clause
The President is the employee who does not have any manager or value in the reportsTo column is NULL .
The following statement uses the LEFT JOIN clause instead of INNER JOIN to include the President:

3) Using MySQL self join to compare successive rows
By using the MySQL self join, you can display a list of customers who locate in the same city by joining the customers table to itself.

In this example, the table customers is joined to itself using the following join conditions:
- c1.city = c2.city makes sure that both customers have the same city.
- c.customerName > c2.customerName ensures that no same customer is included.
In this tutorial, you have learned how to the MySQL self join that to join a table to itself using the INNER JOIN or LEFT JOIN clauses.
Как джойнить таблицу саму на себя
В дополнение к соединению двух или более различных таблиц операция естественного соединения может быть также применена к одной таблице. В этом случае таблица соединяется сама с собой, столбец таблицы сравнивается с тем же столбцом из той же таблицы. Сравнение столбцов с самими собой в одной и той же таблице означает, что имя таблицы появляется дважды в предложении from оператора select. По этой причине у вас должна быть возможность ссылаться на имя одной и той же таблицы дважды. Это можно сделать, используя, по меньшей мере, один псевдоним для таблицы. То же самое верно и для имен столбцов в условии соединения оператора select. Для различения имен двух столбцов вы используете квалифицированные имена. В примере 6.63 таблица department соединяется с собой.

Предложение from в примере 6.63 содержит два псевдонима для таблицы department: t1 и t2. Первое условие в предложении where задает столбцы соединения, в то время как второе условие удаляет ненужные дубликаты, указывая, что каждый отдел сравнивается с другим отделом.