2012-06-14 48 views
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 

什麼是修改我的查詢來做到這一點的好方法?我有一個查詢,然後我拿這些結果,並對該結果集運行第二個查詢(這是不必要的)。

+0

請問您有關'temp.contact'表的更多詳細信息? – Li0liQ

+0

您的查詢和輸出不匹配。 'contact_name'來自哪個表;那應該是'employee_name'?另外,來自哪個'reports_to'表是什麼?那應該是另一個employee.name? Sam Adams的員工ID是1032012嗎?來自temp.employee,temp.employee'的 – gcochard

+0

是正確的? – xelco52

回答

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 
+0

我已經寫出了,但我正在等待消除歧義。 – gcochard