带有递归外键的SQL查询

时间:2011-11-27 23:03:13

标签: sql sql-server-2008 foreign-keys recursive-query

我有一个包含EmployeeID,EmployeeName和ManagerID列的表。 ManagerID是EmployeeID的递归FK。我正在尝试查询表,以便提供作为经理的员工的姓名。我的想法是,如果EmployeeID也是ManagerID,那么Employee将成为Manager。我将ManagerID设置为NOT NULL,因为该人将是经理的经理。当我执行查询时,返回一个空白管理器列。

SELECT EmployeeName AS Manager
FROM Employee E
WHERE E.EmployeeID=E.ManagerID AND
E.ManagerID <> null

3 个答案:

答案 0 :(得分:1)

SELECT EmployeeName AS Manager
FROM Employee 
WHERE EmployeeID IN 
      ( SELECT ManagerID 
        FROM Employee
        WHERE ManagerID IS NOT NULL
      )
  AND ManagerID IS NOT NULL   

SELECT EmployeeName AS Manager                --- show name 
FROM Employee M                               --- of any employee
WHERE EXISTS                                  --- for whom exists
      ( SELECT *                              --- at least one
        FROM Employee E                       --- employee
        WHERE M.EmployeeID = E.ManagerID      --- that is under his management
      )
  AND ManagerID IS NOT NULL                   --- and is not the "root" manager

答案 1 :(得分:1)

我从评论中注意到,您只希望员工成为一线经理。因此,您可以进一步加入以断言没有进一步的子员工:

SELECT distinct M.*
FROM Employee m
join Employee e on e.managerid = m.employeeid
left join Employee s on s.managerid = e.employeeid
WHERE s.employeeid is null;

答案 2 :(得分:-1)

WITH allfkey AS
(

    SELECT referenced_object_id,object_name(referenced_object_id) [object_name],name
    from sys.foreign_keys where parent_object_id=object_id('employee') -- put your table name here

    UNION ALL

   SELECT f.referenced_object_id,object_name(f.referenced_object_id) [object_name],f.name
    from sys.foreign_keys f join allfkey on f.parent_object_id=allfkey.referenced_object_id

)
SELECT * from allfkey