Screen Link: https://app.dataquest.io/m/464/intermediate-joins-in-sql/5/recursive-joins
The query:
select *
FROM
employee e1
inner join employee e2
on e1.reports_to = e2.employee_id
returns the following result:
employee_id|last_name|first_name|title |reports_to|birthdate |
-----------|---------|----------|-------------------|----------|-------------------|
2|Edwards |Nancy |Sales Manager | 1|1958-12-08 00:00:00|
3|Peacock |Jane |Sales Support Agent| 2|1973-08-29 00:00:00|
4|Park |Margaret |Sales Support Agent| 2|1947-09-19 00:00:00|
5|Johnson |Steve |Sales Support Agent| 2|1965-03-03 00:00:00|
6|Mitchell |Michael |IT Manager | 1|1973-07-01 00:00:00|
7|King |Robert |IT Staff | 6|1970-05-29 00:00:00|
8|Callahan |Laura |IT Staff | 6|1968-01-09 00:00:00|
However, if I swap e1
and e2
, that is:
select *
FROM
employee e1
inner join employee e2
on e2.reports_to = e1.employee_id <---- changed
I get the following:
employee_id|last_name|first_name|title |reports_to|birthdate |
-----------|---------|----------|---------------|----------|-------------------|
1|Adams |Andrew |General Manager| |1962-02-18 00:00:00|
2|Edwards |Nancy |Sales Manager | 1|1958-12-08 00:00:00|
2|Edwards |Nancy |Sales Manager | 1|1958-12-08 00:00:00|
2|Edwards |Nancy |Sales Manager | 1|1958-12-08 00:00:00|
1|Adams |Andrew |General Manager| |1962-02-18 00:00:00|
6|Mitchell |Michael |IT Manager | 1|1973-07-01 00:00:00|
6|Mitchell |Michael |IT Manager | 1|1973-07-01 00:00:00|
My question is how to use the correct columns in the ON
clause?