查找层次结构中的元素

时间:2013-02-06 17:17:30

标签: sql-server tsql common-table-expression hierarchical

我正在尝试使用WITH的T-SQL创建分层查询。我想做的是,例如,直接或间接地找出John是否是Ryan的老板?

如何为此编写查询?

1 个答案:

答案 0 :(得分:2)

WITH BossOf AS(
   SELECT bossId, Id From Employees
       UNION ALL
   SELECT b.bossId, e.Id 
   FROM Employees AS e
   INNER JOIN BossOf b ON b.Id = e.bossId
)
SELECT * FROM BossOf
   WHERE Id = 'Ryan'

就像你可以用BossOf做的一个例子......

WITH BossOf AS(
   SELECT bossId, Id From Employees
       UNION ALL
   SELECT b.bossId, e.Id 
   FROM Employees AS e
   INNER JOIN BossOf b ON b.Id = e.bossId
)
SELECT * FROM Employees
    WHERE Id IN (SELECT BossId 
                    FROM BossOf
                    Where Id = 'Ryan')

甚至

WITH BossOf AS(
   SELECT bossId, Id From Employees
       UNION ALL
   SELECT b.bossId, e.Id 
   FROM Employees AS e
   INNER JOIN BossOf b ON b.Id = e.bossId
)
SELECT COUNT(*) FROM BossOf
   WHERE Id = 'Ryan'
   AND BossId = 'John'