Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Parent and Child Records

How do i select all the employees of a company and its child companies?

Using SQL Server 2008

Employee

Id | Name | CompanyId  

Company

Id | Name | ParentCompanyId  

Example:

1 Microsoft 0

2 Microsoft India 1

3 Microsoft Spain 1

I have this below query which gives only employees from Microsoft and not from Microsoft India & Spain.

SELECT Id, Name FROM Employee WHERE CompanyId=1

I am not good in SQL. Help me on this.

like image 206
Billa Avatar asked Mar 17 '13 14:03

Billa


2 Answers

Use a CTE to build the company hierarchy, then join this back to the Employees table:

with CompanyHierarchy as
(
  select Id
  from Company
  where Id = 1
  union all
  select c.Id
  from Company c
    inner join CompanyHierarchy ch on c.ParentCompanyId = ch.Id
)
select e.*
from CompanyHierarchy ch
  inner join Employees e on ch.Id = e.CompanyId

SQL Fiddle with demo.

You can also substitute a CompanyId variable into the anchor portion of the CTE if you want to parameterize the statement:

with CompanyHierarchy as
(
  select Id
  from Company
  where Id = @CompanyId
  union all
  select c.Id
  from Company c
    inner join CompanyHierarchy ch on c.ParentCompanyId = ch.Id
)
select e.*
from CompanyHierarchy ch
  inner join Employees e on ch.Id = e.CompanyId

SQL Fiddle with demo, now with added hierarchy levels.

like image 162
Ian Preston Avatar answered Oct 09 '22 17:10

Ian Preston


SELECT 
   employee.name,
   company.id 
FROM employee
INNER JOIN company 
On employee.companyId= company.id
WHERE company.id IN (1,2,3)
like image 26
Nikki Duffy Avatar answered Oct 09 '22 17:10

Nikki Duffy