You can use Common Table Expressions (CTE) to solve this problem. CTEs can be used for recursion, as Andrew noted (see. The excellent link that Andrey included in his post). Let's say you have a table as follows:
create table Person ( PersonId int primary key, Name varchar(25), ManagerId int foreign Key references Person(PersonId) )
and paste the following data into the table:
insert into Person (PersonId, Name, ManagerId) values (1,'Bob', null), (2, 'Steve',1), (3, 'Tim', 2) (4, 'John', 3), (5, 'James', null), (6, 'Joe', 5)
then we need a request that will return to anyone who directly or indirectly tells Bob that Steve, Tim and John will be. We do not want to return James and Bob because they are not telling anyone, or Joe because he is telling James. This can be done using a CTE request as follows:
WITH Managers AS (
This query returns the correct results:
PersonId Name ManagerId ----------- ------------------------- ----------- 2 Steve 1 3 Tim 2 4 John 3
Edit: This answer is valid if the OP uses SQL Server 2005 or higher. I do not know if this syntax is valid in MySQL or Oracle.