MySQL Tutorial
A SELF JOIN in MySQL is a type of join where a table is joined with itself.
SELECT A.column_name, B.column_name FROM table_name A JOIN table_name B ON A.common_column = B.common_column;
A and B → Aliases for the same table to treat them as two separate tables.ON → Specifies the condition for matching rows.Consider an Employees table where each employee has a manager.
The table has a manager_id column that refers to the employee_id of their manager.
|
employee_id |
name |
manager_id |
|---|---|---|
|
1 |
Alice |
NULL |
|
2 |
Bob |
1 |
|
3 |
Charlie |
1 |
|
4 |
David |
2 |
|
5 |
Eve |
3 |
The following SQL statement display employee names with their manager names.
Try it yourself
|
Employee |
Manager |
|---|---|
|
Alice |
NULL |
|
Bob |
Alice |
|
Charlie |
Alice |
|
David |
Bob |
|
Eve |
Charlie |
NULL as the manager.