Reference:http://blog.sqlauthority.com/2010/07/08/sql-server-the-self-join-inner-join-and-outer-join/
USE TempDbGO-- Create a TableCREATE TABLE Employee(EmployeeID INT PRIMARY KEY,Name NVARCHAR(50),ManagerID INT)GO-- Insert Sample DataINSERT INTO EmployeeSELECT 1, 'Mike', 3UNION ALLSELECT 2, 'David', 3UNION ALLSELECT 3, 'Roger', NULLUNION ALLSELECT 4, 'Marry',2UNION ALLSELECT 5, 'Joseph',2UNION ALLSELECT 7, 'Ben',2GO-- Check the dataSELECT *FROM EmployeeGO
We will now use inner join to find the employees and their managers’ details.
-- Inner JoinSELECT e1.Name EmployeeName, e2.name AS ManagerNameFROM Employee e1INNER JOIN Employee e2ON e1.ManagerID = e2.EmployeeIDGO
From the result set, we can see that all the employees who have a manager are visible. However we are unable to find out the top manager of the company as he is not visible in our resultset. The reason for the same is that due to inner join, his name is filtered out. Inner join does not bring any result which does not have manager id. Let us convert Inner Join to Outer Join and then see the resultset.
-- Outer JoinSELECT e1.Name EmployeeName, ISNULL(e2.name, 'Top Manager') ASManagerNameFROM Employee e1LEFT JOIN Employee e2ON e1.ManagerID = e2.EmployeeIDGO
Once we convert Inner Join to Outer Join, we can see the Top Manager as well. Here we have seen how Self Join can behave as an inner join as well as an outer join.
As I said earlier, many of you know these details, but there are many who are still confused about this concept. I hope that this concept is clear from this post.
No comments:
Post a Comment