使用 CTE 构建公司层次结构,然后将其连接回员工表:
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 与演示。
CompanyId
如果要参数化语句,还可以将变量替换为CTE 的锚部分:
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,现在增加了层次结构。