简体   繁体   中英

Self Join in SQL explanation

How does self join work when I link the same columns of two tables?

For example, let the table be:

在此处输入图像描述

And my code is:

SELECT a.*,b.*
  FROM table a JOIN table b ON (a.id=b.id) AND (a.name=b.name)

What will happen internally when the table is SELF JOIN-ed and why?

Your sample of a self-join does not give justice to the intent. Maybe this scenario will help better explain it. You have a database with your company. In it is a table of all employees and who that employee reports to (ie, manager). So, this is a table pointing to itself such as

Employee table
EmployeeID   Name    ManagerID
1            Adam    3
2            Mark    1
3            Sally   0
4            James   1
5            George  3
6            Jill    3
7            Tom     0
8            Brian   2

So, this shows a hierarchy of multiple levels. For example, #8 Brian's manager is #2 Mark, but Mark's manager is #1 Adam, who finally reports to #3 Sally, but #5 George also reports directly to #3 Sally. Make sense?

So now, a self-join might be something like

Select
      emp.EmployeeID,
      emp.Name,
      coalesce( mgr.Name, '(no manager)' ) as ReportsToManager
   from
      Employee emp
         LEFT JOIN Employee mgr
            on emp.ManagerID = emp.EmployeeID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM