thanks for reading. I'm sure there is a sensible way to do what I am trying to do, but my lack of DB experience is letting me down.
I'm going to simplify greatly to pin point my question..... I have 3 tables
- a table called employees (employee_id, name, parent_id etc).
- a table called projects (project_id, project_name etc)
- a table linking the two called assigned_projects (id, employee_id, project_id)
The Employee table is up to 6 levels deep (although can be as shallow as 3 in some places) and contains about 900 employees. e.g.
A
/ \
B C
/|\
D E F
Now, projects can be assigned at any level. If I assign it to employee A, then it should be linked also to all his subordinates (B->F). If I assign it to C, then it should be linked to D+E+F, but I would also want to see that it is within A's remit.
When I bring up an employee's profile, I am using a CTE anchored at the appropriate employee to recursively find all subordinates. The issue I have is, for each of those subordinates, how to I join to the assigned_projects table to see what projects are in this person's remit?
Options I considered:
- do the CTE piece first, then within the php, iterate through all employee_ids to run separate queries that pull project_ids from the assigned_projects table
- when initially assigning a project to an employee, iterate through the tree and add an entry to assigned_projects for each appropriate employee. Problem here is that if employees move around the tree (change jobs), I want them to inherit/remove projects accordingly.
To be clear, when bringing up profile of C, I would want to see all projects assigned to A,C,D,E,F. When bringing up profile of B, I would want to see all projects relating to A or B.
It seems like there should be a way of doing this in SQL using some cleverness that I just dont have the experience for? Or should I change my table structure.... I'm open to that too.
Hope I explained that properly. Thanks for any help, appreciate your time.