I have 2 tables: Users and Roles.
Users table columns:
UserId FirstName Lastname
Roles table columns:
RoleId UserId ParentId
I want to be able to fetch date from these 2 tables representing a column named ParentName.
So lets say I have these data:
Users table:
UserId FirstName Lastname
1 John Doe
2 Jane Smith
3 John Smith
Roles table:
RoleId UserId ParentId
1 1 NULL
2 2 1
3 3 2
So I want to have this table:
UserId FirstName Lastname RoleId ParentId ParentName
1 John Doe 1 NULL NULL
2 Jane Smith 2 1 John Doe
3 John Smith 3 2 Jane Smith
I tried but I couldn't. I tried INNER JOIN, OUTER JOIN, Subqueries but I Couldn't get what I wanted.
In joining 2 tables together I have this:
SELECT UserId, FirstName, Lastname, RoleId, ParentId
FROM Users INNER JOIN Roles ON Users.UserId = Roles.UserId
And In joining a self recursive Roles table I have this:
SELECT ChildUsers.UserId, ChildUsers.RoleId, ParentUsers.UserId, ParentUsers.RoleId, Users.LastName
FROM Roles AS ChildUsers
LEFT JOIN Roles AS ParentUsers ON ChildUsers.ParentId = ParentUsers.RoleId
INNER JOIN Users ON Users.UserId = ParentUsers.UserId
But I couldn't get what I wanted. How can I get that?
-----------UPDATE---------------
Here is my own solution:
SELECT Roles.RoleID, LastName, Parent.ParentName FROM
Roles INNER JOIN Users ON Users.UserID = Roles.UserID LEFT JOIN
(SELECT LastName AS ParentName, RoleID FROM Users INNER JOIN Roles ON Users.UserID = Roles.UserID) Parent ON Parent.RoleID = Roles.ParentID
But I choose LukStorms solution as the answer.