Monday, August 16, 2010

Self Join

Self join is an interesting subject. Why join to the same table? There are situations where you need to get some information from the same table but not from the same row of record. The following may help you to understand.

In a company, I have a employee table listing the employee information. In the employee table I list the employee information plus the manager\'s id ( to save space). Now I want to list the employee information but want to know the manager\'s name instead of id.

Since the manager is also an employee listed in the table, the only way to get the information is via self joins. The following is the sql.

select a.employee_name as employee,b.employee_name as manager from tbl_employee as a inner join tbl_employee as b on a.manager_id = b.employee_id

Here you can see that it is no differen from any other joins except that the same table is used.

No comments:

Post a Comment