1

我很难理解 MS SQL 中应该是一个非常简单的查询。我有两张桌子:EmployeesDepartments

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

DepartmentsDepartmentID, DepartmentName, ... ,ManagerID组成

Employees.DepartmentID到有关系,和Departments.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

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

4

3 回答 3

3

我建议不要使用子查询(它们要贵得多),而支持另一个联接。第二个连接将从 dept 表返回到 emp 表,在部门经理 ID 上再到员工的 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 与子查询链接的好帖子。

于 2012-10-29T18:29:35.430 回答
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

注意:未经测试的代码,但想法是您可以简单地将员工表别名为“m”(对于经理)并加入到它,键入经理的EmployeeId

于 2012-10-29T18:28:00.487 回答
0

在您的选择子句中

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

您需要按部门 ID 过滤。

就目前而言,它将返回所有部门的所有经理?

于 2012-10-29T18:24:57.927 回答