Reputation: 3
I have two tables PERSON
and PERSONRELATION
.
On the PERSON
table I have the columns PERSONpk
, FIRSTNAME
, and LASTNAME
.
On the PERSONRELATION
table I have MANAGER1fk
which is the a fk for PERSONpk
.
I am trying to join the two tables, bring over all the fields above and self join back to add the MANAGERFIRSTNAME
and MANAGERLASTNAME
. Here is what I have done but it apparently isn't correct:
Select PERSONpk, MANAGER1FK,e.FIRSTNAME,e.LastName,m.FIRSTNAME,M.LASTNAME
FROM dbo.PERSON e
INNER JOIN dbo.PERSONRELATION rel
ON rel.PERSONFK = PERSONPK
INNER JOIN dbo.PERSON m ON e.PERSONpk = m.MANAGER1FK
Upvotes: 0
Views: 1449
Reputation: 35323
Three issues:
Table personrelation contains the FK for both the employee and the manager to person; thus you need to join the 2nd fk field from personrelation (MANAGER1fk) (and this isn't a self join) If the hierarchy were all maintained in person it would be a self join.
SELECT e.PERSONpk
, rel.MANAGER1FK
, e.FIRSTNAME
, e.LastName
, m.FIRSTNAME
, M.LASTNAME
FROM dbo.PERSON e
INNER JOIN dbo.PERSONRELATION rel
ON rel.PERSONFK = e.PERSONPK
INNER JOIN dbo.PERSON m
ON m.PERSONpk = rel.MANAGER1FK
Upvotes: 1