I'm using mysql for one on my web applications. The application table contains a supervisor table and an employee table. employee table contains information about each employee. The supervisor table contains two columns as follows.
supervisor_id -> which is employee id of the supervisor
subordinate_id -> which is the employee id of the subordinate.
Each subordinate can have multiple supervisors and one supervisors subordinates can be a supervisor of of some other employee. So the table records can be ass follows.
supervisor_id | subordinate_id
1 | 2
1 | 3
2 | 4
4 | 5
3 | 6
3 | 4
In the above example there is a supervisor chain. Supervisor 1 has 2, 3, 4, 5 and 6 as his subordinates. Supervisor 2 has 4, 5 as subordinates. And also it can have multiple supervisors for a subordinate.
When I querying for all subordinates for supervisor 2 currently I use a query like following.
public function getSubordinate($id) {
$query = "SELECT * FROM supervisor WHERE subordinate_id = $id";
// get results and return
}
So what I'm currently do is first send the id as 2 to get its immediate subordinates. Then for each and every resulting subordinates I run the query again and again to get the full subordinate chain.
This is okay with small set of data. But this supervisor table will have thousands of data so I have to do thousands of queries to find the supervisor chain and it takes times to give results.
Since subordinates can have multiple supervisors the nested set will not be a exact answer for this.
I went through this solution also . http://www.codeproject.com/Articles/22824/A-Model-to-Represent-Directed-Acyclic-Graphs-DAG-o
But when I use this method it will have millions of data with that table. and it is inefficient.
My problem is there any efficient way to do this. Is there any problem with my table structure which prevent me to do this kind of query efficiently.