I have three tables that I use which has proved this problem to be way out of my league.
The first is the hierachy table which looks like this
USER_ID, USER_LEVEL, Store_Manager_ID, Team_Manager_ID
------------------------------------------------------
1, 0, -, -
2, 1, 1, -
3, 2, 1, 2
4, 2, 1, 2
5, 2, 1, 2
This just shows the hierachy of the user. So user 1 has a level of 0 which means he is th store manager and so he has no store manager on top of him so his store manager id is nothing and team manager is obviously nothing.
The second user is the team manager and so level = 1 and store manager is 1(the first guy)
The third, forth and fifth are workers under 1 and 2 respectively.
The second is a login table which looks like this
USER_ID, EMAIL
--------------------------
1, john.smith@gmail.com
2, ron.jones@gmail.com
3, tom.graham@gmail.com
4, bill.small@gmail.com
The email is the login, no password.
The third is an alias table which looks like this
USER_ID, ALIAS_ID
--------------------
2, 5
The alias tables shows how user 5 is an alias of user 2. So he is the same person and has the same login. However he can be in two places in the hierachy at once i.e. a team manager and a worker at the same time.
My question is.
If I know that user 2 will be logging in as his alias, i.e. a worker before login.
When user 2 logs in, how can I select the id of the leader of the users account based on the level.
For example if I logged in as ron.jones@gmail.com (user 2) under my alias account.
The alias id of user 2 is 5 and based on the hierachy user 5 is level 2 i.e. a worker and so I should return the id of his team manager not his store manager.
So I would then return 2, i.e. himself (a little bizarre in the this case but besides the point)
This will give the answer you are looking for (if I understand the question correctly):