嵌套的Select语句?

时间:2008-12-18 07:24:14

标签: sql sql-server

您好我是sql的新手,但已经通过了我需要查询数据库的工作(MS SQL 2005)我需要返回给出HeadID的所有工作人员。(下表) 因此,我需要获得所有与HeadID匹配的经理,然后通过ManagerID获得与这些经理匹配的所有工作人员。我该怎么做?任何有助于我更好地搜索解决方案的帮助或任何sql术语都将非常感激。 感谢

tb_Head: HeadID

tb_Manager: 经理ID, HeadID,

tb_Worker: WorkerID, 经理ID,

3 个答案:

答案 0 :(得分:2)

一种简单的方法是做这样的事情:

select * from tb_Worker
  join tb_Manager on tb_Worker.ManagerID = tb_Manager.ManagerID
  join tb_Head on tb_Manager.HeadID = Head.HeadID
  where tb_Head.HeadID = <given value>

调整表名并根据需要选择列。

答案 1 :(得分:1)

使用公用表表达式

USE AdventureWorks;
GO
WITH DirectReports(ManagerID, EmployeeID, EmployeeLevel) AS 
(
    SELECT ManagerID, EmployeeID, 0 AS EmployeeLevel
    FROM HumanResources.Employee
    WHERE ManagerID IS NULL
    UNION ALL
    SELECT e.ManagerID, e.EmployeeID, EmployeeLevel + 1
    FROM HumanResources.Employee e
        INNER JOIN DirectReports d
        ON e.ManagerID = d.EmployeeID 
)
SELECT ManagerID, EmployeeID, EmployeeLevel 
FROM DirectReports ;
GO

答案 2 :(得分:0)

听起来你想要使用递归CTE。 books online article谈论你的情景。这是我刚刚在另一个stackoverflow文章中使用的一组示例代码......

CREATE TABLE dbo.ctetest (employeeid int primary key not null, managerid int null);

INSERT INTO dbo.ctetest (employeeid, managerid) SELECT 1, NULL;
INSERT INTO dbo.ctetest (employeeid, managerid) SELECT 2, 1;
INSERT INTO dbo.ctetest (employeeid, managerid) SELECT 3, 1;
INSERT INTO dbo.ctetest (employeeid, managerid) SELECT 4, 2;
INSERT INTO dbo.ctetest (employeeid, managerid) SELECT 5, 2;
INSERT INTO dbo.ctetest (employeeid, managerid) SELECT 6, 3;
INSERT INTO dbo.ctetest (employeeid, managerid) SELECT 7, 2;
INSERT INTO dbo.ctetest (employeeid, managerid) SELECT 8, 5;
INSERT INTO dbo.ctetest (employeeid, managerid) SELECT 9, 4;
INSERT INTO dbo.ctetest (employeeid, managerid) SELECT 10, 6;
INSERT INTO dbo.ctetest (employeeid, managerid) SELECT 11, 6;

WITH recursivecte (employeeid, managerid, level)
AS
(SELECT employeeid
    , managerid
    , 'level' = 0
FROM dbo.ctetest
WHERE managerid IS NULL
UNION ALL
SELECT ct.employeeid
    , ct.managerid
    , 'level' = rc.level + 1
FROM dbo.ctetest ct
JOIN recursivecte rc
    ON ct.managerid = rc.employeeid)

SELECT *
FROM recursivecte rc

这应该为您提供从一个级别到另一个级别的每个员工的层次结构。如果要返回有关下一个最高级别(如管理器名称)的信息,则只需将rc.managername添加到UNION ALL的第二部分,将列添加到CTE表(即WITH recursivecte(employeeid,managerid) ,级别)部分,并在声明的第一部分给予持有者。