来自同一数据表的SQL SubQuery

时间:2012-10-29 18:17:21

标签: sql join subquery

我无法绕过MS SQL中非常简单的查询。我有两个表:EmployeesDepartments

Employees由标准项组成:ID (pkey int)FNameLName,...,DepartmentID

DepartmentsDepartmentIDDepartmentName,...,ManagerID组成。

Employees.DepartmentIDDepartments.DepartmentID之间存在关系,Departments.ManagerIDEmployees.EmployeeID之间存在关系。

换句话说,每个员工都有一个部门,每个部门都有一个也是员工的经理。

我正在尝试创建一个显示员工姓名,......,部门和部门经理的视图。

使用此代码时,我一直收到错误,表示返回了多个值:

SELECT
Employees_1.EmployeeID, Employees_1.FirstName, Employees_1.LastName, 
Departments_1.DepartmentName,
(SELECT
    dbo.Employees.LastName
    FROM dbo.Employees 
    INNER JOIN dbo.Departments
      ON dbo.Departments.DepartmentManager = dbo.Employees.EmployeeID
) AS ManagerName
FROM dbo.Employees AS Employees_1
INNER JOIN dbo.Departments AS Departments_1 
  ON Employees_1.Department = Departments_1.DepartmentID 
  AND Employees_1.EmployeeID = Departments_1.DepartmentManager

有关如何根据第二个表中的关系连接回同一个表(不同行)的任何想法?

3 个答案:

答案 0 :(得分:3)

我建议反对子查询(它们更贵),支持另一个加入。 第二次加入将从dept表返回到部门经理ID上的emp表到员工的Employee ID。

(为了清楚起见,我添加了列别名 - 它们根本不需要)

SELECT
    emp.EmployeeID          "EmpID",
    emp.FirstName           "EmpFirst",
    emp.LastName            "EmpLast",
    dept.DepartmentName     "DeptName",
    deptMgrEmp.FirstName    "MgrFirst",
    deptMgrEmp.LastName     "MgrLast"
FROM
    dbo.Employees as emp
    LEFT JOIN dbo.Departments as dept
    on emp.DepartmentID = dept.DepartmentID
    LEFT JOIN dbo.Employees as deptMgrEmp
    on dept.ManagerID = deptMgrEmp.EmployeeID

这是一个讨论JOIN与子查询link的好线程。

答案 1 :(得分:2)

SELECT
  e.EmployeeId,
  e.FirstName,
  e.LastName,
  d.DepartmentName,
  m.EmployeeId as ManagerId
  m.FirstName as ManagerFirstName,
  m.LastName as ManagerLastName
FROM
  dbo.Employees e 
  JOIN dbo.Departments d
    ON d.DepartmentId = e.DepartmentId
  JOIN dbo.Employees m
    ON d.DepartmentManager = m.EmployeeID

注意:未经测试的代码,但您的想法是,您可以简单地将Employees表别名为“m”(对于Managers)并加入回来,键入管理器的EmployeeId

答案 2 :(得分:0)

在你的select子句中

(SELECT dbo.Employees.LastName FROM dbo.Employees INNER JOIN dbo.Departments ON dbo.Departments.DepartmentManager = dbo.Employees.EmployeeID)

您需要按部门ID进行过滤。

目前,它将归还所有部门的所有管理人员?