66.8k views
5 votes
SELF JOIN done with the help of table aliases Example:

User Eoinoc
by
7.1k points

1 Answer

5 votes

Final answer:

A self-join allows a table to be joined with itself using table aliases. It is useful for comparing records within the same table.

Step-by-step explanation:

In self-join, a table can be joined with itself using table aliases. This allows us to retrieve information by comparing records within the same table. Let's consider an example to illustrate this:

We have a table called 'Employees' with columns 'ID' and 'ManagerID'. To find the employees who report to the same manager, we can use a self-join like this:

  1. SELECT e1.ID, e2.ID
  2. FROM Employees e1, Employees e2
  3. WHERE e1.ManagerID = e2.ManagerID
  4. AND e1.ID <> e2.ID;

In this example, we are joining the 'Employees' table with itself using the aliases 'e1' and 'e2'. We compare the 'ManagerID' column of these aliases to find employees who report to the same manager. The 'e1.ID <> e2.ID' condition ensures that we get distinct pairs of employees.

User Tarun Modi
by
7.3k points