Guest User

Untitled

a guest
Oct 17th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. Self-join
  2.  
  3. A self-join is joining a table to itself.[6]
  4. [edit]Example
  5. A query to find all pairings of two employees in the same country is desired. If there were two separate tables for employees and a query which requested employees in the first table having the same country as employees in the second table, a normal join operation could be used to find the answer table. However, all the employee information is contained within a single large table.[7]
  6. Consider a modified Employee table such as the following:
  7. Employee Table
  8. EmployeeID LastName Country DepartmentID
  9. 123 Rafferty Australia 31
  10. 124 Jones Australia 33
  11. 145 Steinberg Australia 33
  12. 201 Robinson United States 34
  13. 305 Smith Germany 34
  14. 306 John Germany NULL
  15.  
  16. An example solution query could be as follows:
  17. SELECT F.EmployeeID, F.LastName, S.EmployeeID, S.LastName, F.Country
  18. FROM Employee F
  19. INNER JOIN Employee S ON F.Country = S.Country
  20. WHERE F.EmployeeID < S.EmployeeID
  21. ORDER BY F.EmployeeID, S.EmployeeID;
  22. Which results in the following table being generated.
  23. Employee Table after Self-join by Country
  24. EmployeeID LastName EmployeeID LastName Country
  25. 123 Rafferty 124 Jones Australia
  26. 123 Rafferty 145 Steinberg Australia
  27. 124 Jones 145 Steinberg Australia
  28. 305 Smith 306 John Germany
  29.  
  30. For this example:
  31. F and S are aliases for the first and second copies of the employee table.
  32. The condition F.Country = S.Country excludes pairings between employees in different countries. The example question only wanted pairs of employees in the same country.
  33. The condition F.EmployeeID < S.EmployeeID excludes pairings where the EmployeeID of the first employee is greater than or equal to the EmployeeID of the second employee. In other words, the effect of this condition is to exclude duplicate pairings and self-pairings. Without it, the following less useful table would be generated (the table below displays only the "Germany" portion of the result):
  34. EmployeeID LastName EmployeeID LastName Country
  35. 305 Smith 305 Smith Germany
  36. 305 Smith 306 John Germany
  37. 306 John 305 Smith Germany
  38. 306 John 306 John Germany
  39.  
  40. Only one of the two middle pairings is needed to satisfy the original question, and the topmost and bottommost are of no interest at all in this example.
Add Comment
Please, Sign In to add comment