A self join in MySQL is a join where a table is joined with itself. This is useful when you have a table that contains hierarchical data, such as an employee table where each employee has a manager who is also an employee. In this case, you can use a self join to retrieve information about an employee and their manager.
The syntax for a self join is similar to that of a regular join. You specify the table name twice and use table aliases to distinguish between the two instances of the table. Here’s an example:
SELECT e.name AS employee_name, m.name AS manager_name FROM employee e JOIN employee m ON e.manager_id = m.id;
In this example, the
employee table is joined with itself using the
manager_id column to match employees with their managers. The
m aliases are used to distinguish between the two instances of the table. The result set will contain the names of employees and their respective managers.
Note that in a self join, it’s important to use table aliases to avoid ambiguity in column names. It’s also important to ensure that the join condition is correct to avoid creating an infinite loop.