How To Use Self Join In Sql Server
Self Join in SQL Server 2000/2005 helps in retrieving the records having some relation or similarity with other records in the same database table. A common example of employees table can do more clearly about the self join in sql. Self join in sql means joining the single table to itself. It creates the partial view of the single table and retrieves the related records. You can use aliases for the same table to set a self join between the single table and retrieve the records satisfying the condition in where clause.
For self join in sql you can try the following example:
Create table employees:
Now to get the names of managers from the above single table you can use sub queries or simply the self join.
Self Join SQL Query to get the names of manager and employees:
select e1.emp_name 'manager',e2.emp_name 'employee'
from employees e1 join employees e2
on e1.emp_id=e2.emp_manager_id
Result:
For self join in sql you can try the following example:
Create table employees:
emp_id | emp_name | emp_manager_id |
1 | John | Null |
2 | Tom | 1 |
3 | Smith | 1 |
4 | Albert | 2 |
5 | David | 2 |
6 | Murphy | 5 |
7 | Petra | 5 |
Now to get the names of managers from the above single table you can use sub queries or simply the self join.
Self Join SQL Query to get the names of manager and employees:
select e1.emp_name 'manager',e2.emp_name 'employee'
from employees e1 join employees e2
on e1.emp_id=e2.emp_manager_id
Result:
manager | employee |
John | Tom |
John | Smith |
Tom | Albert |
Tom | David |
David | Murphy |
David | Petra |
No comments:
Post a Comment