0

在我写的查询方面需要帮助:

我有三张桌子

公司

id     name
1      Gary's

员工

id     name         company_id
1      Tim Jones       1
2      Sam Adams       1

汇报给

employee_id      reports_to_id
     1                 2    

我目前的查询是:

select 
   temp.company.name as comp_name, 
   temp.employee.name as employee_name, 
   temp.employee.id as employee_id 
from temp.employee, temp.employee
where temp.company.id = temp.employee.company_id and temp.company.id = 1

这给了我以下输出:

comp_name    employee_name     employee_id
 Gary's       Tim Jones           1

我需要这样的东西:

comp_name     employee_name    reports_to
Gary's         Tim Jones        Sam Adams

修改我的查询以执行此操作的好方法是什么?我有一个查询,然后我获取这些结果并针对该结果集运行第二个查询(这是非常不必要的)。

4

1 回答 1

4

假设一名员工只向一个人报告,那么我们可以拥有(没有链接表)

Employee  (Id, Name, CompanyId, ReportsToId)
Company (Id, Name)

然后你可以有一个类似于

select e.Name EmployeeName, c.Name CompanyName, r.Name ReportsTo
from
    Employee e
        inner join Company c on e.CompanyId = c.Id
        inner join Employee r on e.ReportsToId = r.Id
where
    e.CompanyId = 1

如果员工向多人报告,那么我们将使用链接表

Employee  (Id, Name, CompanyId)
EmployeeReportsTo (EmployeeId, ManagerId)
Company (Id, Name)

select e.Name EmployeeName, c.Name CompanyName, r.Name ReportsTo
from
    Employee e
        inner join Company c on e.CompanyId = c.Id
        inner join EmployeeReportsTo ert on ert.EmployeeId = e.Id
        inner join Employee r on ert.ManagerId = r.Id
where
    e.CompanyId = 1
于 2012-06-14T17:51:30.220 回答