Joining a table to itself is called self join.
Example of Self Join
Suppose you have a table that stores an employee identification number, the employee’s name, and the employee identification number of the employee’s manager. You might want to produce a list of all employees and their managers’ names. The problem is that the manager name does not exist as a category in the table:
SELECT * FROM EMP;
ID | NAME | MGR_ID |
---|---|---|
1 | JOHN | 0 |
2 | MARY | 1 |
3 | STEVE | 1 |
4 | JACK | 2 |
5 | SUE | 2 |
In the following example, we have included the table EMP twice in the FROM clause of the query, giving the table two aliases for the purpose of the query. By providing two aliases, it is as if you are selecting from two distinct tables. All managers are also employees, so the JOIN condition between the two tables compares the value of the employee identification number from the first table with the manager identification number in the second table. The first table acts as a table that stores employee information, whereas the second table acts as a table that stores manager information:
SELECT E1.NAME, E2.NAME
FROM EMP E1, EMP E2
WHERE E1.MGR_ID = E2.ID;
Name | Name |
---|---|
MARY | JOHN |
STEVE | JOHN |
JACK | MARY |
SUE | MARY |
[Source: Sams Teach Yourself SQL in 24 Hours By Ryan Stephens, Ron Plew, Arie Jones]
Why use self join
While self-joins rarely are used on a normalized database, you can use them to reduce the number of queries that you execute when you compare values of different columns of the same table.
When you use self-joins, consider the following guidelines:
You must specify table aliases to reference two copies of the table. Remember that table aliases are different from column aliases. Table aliases are designated as the table name followed by the alias.
When you create self-joins, each row matches itself and pairs are repeated, resulting in duplicate rows. Use a WHERE clause to eliminate these duplicate rows [Microsoft SQL Server 7.0 data warehousing training]
[Source: Microsoft SQL Server 7.0 data warehousing training]
No comments:
Post a Comment