2011-11-27 68 views
1

我有一個包含EmployeeID,EmployeeName和ManagerID列的表。 ManagerID是EmployeeID的遞歸FK。我試圖查詢表格,以便提供經理人員的名字。我的思路是,如果員工的EmployeeID也是ManagerID,則員工將成爲經理。我將ManagerID設置爲NOT NULL,因爲那個人將是經理的經理。當我執行查詢時,返回一個空白管理員列。使用遞歸外鍵的SQL查詢

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

您正在使用什麼數據庫? – Bert

+0

我正在使用SQL Server 2008 –

回答

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 
+0

感謝您的幫助。我有一個建立在這個問題上的問題。如果我只想要沒有經理的人的名字,爲什麼插入「<>」而不是「=」不起作用?不應該把不等於上面的查詢的相反?再次感謝。 –

+0

找到所有沒有經理的人會更容易,只需使用:'SELECT EmployeeName FROM Employee WHERE ManagerID IS NULL'。不需要子查詢。 –

+0

糟糕,我在那裏有一個拼寫錯誤,我的意思是那些不是經理的員工,即由上述查詢產生的第一線經理管理的員工。 –

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; 
-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