This was a question which I was asked in an interview recently:
You have various types of users in an organization : Junior
(is bossed by) Supervisor
(is bossed by) Manager
(is bossed by) CEO
.
We agreed upon this single simplified table schema. Users : {userId, userName, UserType(J, S, M, C), bossUserId}
Q : Write a single query to determine the complete organizational hierarchy of a Junior
employee with userId = 11.
Sample Data :
The answer would be => PQR2 --> GHI2 --> DEF1 --> ABC1
This was my solution :
select e1.userName, e2.userName, e3.userName, e4.userName from
abc e1 inner join users e2 on e1.bossUserId = e2.userId
inner join users e3 on e2.bossUserId = e3.userId
inner join users e4 on e3.bossUserId = e4.userId
where e1.userId = 11;
I do realize that self joining 4 times is horrible, but I was not able to think of anything else. The interviewer told me that there is a better way and that the data will show up columnwise
. (using a maximum of 2 self joins
, if at all)
Another possibility was to write a stored procedure, but again it is not a single query.
Can anyone help me with this?