加入三个表(链接表)

时间:2012-06-14 17:37:08

标签: sql join

需要帮助我写的查询:

我有三张桌子

公司

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

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

1 个答案:

答案 0 :(得分: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