1

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

我该如何为此编写查询?

4

1 回答 1

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'
于 2013-02-06T17:24:25.823 回答