A self-join is a SQL join that joins a table to itself. It is particularly useful when dealing with hierarchical data or when you need to compare rows within the same table.
Consider a table named Employees
with columns EmployeeID
, EmployeeName
, and ManagerID
, where ManagerID
references the EmployeeID
of the employee's manager.
We want to retrieve the names of employees along with the names of their
managers.
SELECT e.EmployeeName AS Employee, m.EmployeeName AS
Manager FROM Employees e JOIN Employees m ON
e.ManagerID = m.EmployeeID;
In this example, the Employees table is self-joined. The
alias e
is used for the main
instance of the Employees table representing employees, and the alias m
is used for the joined
instance representing managers. The join condition e.ManagerID = m.EmployeeID
matches each employee's manager ID with the corresponding manager's employee
ID, effectively retrieving the name of each employee along with the name of
their manager.
Comments
Post a Comment