MySQL - 在一个表中连接两个ID

时间:2012-10-12 21:42:28

标签: mysql

此查询是关于仅在一个表中连接两个ID的问题。

表:雇主

Employee no.  Lastname  Firstname  reports to  title
111           Garret    Mike       333         sales manager
333           Frank     Savage     444         President

我的问题是如何连接此表?

表格应该是:

Employee no.  Lastname  Firstname  reports to(Supervisor No.)  Firstname   Lastame
111           Garret    Mike       333                         Frank       Savage

我试过了:

Select Employee no., Lastname, Firstname, reports to AS SuperVisorNumber, firstname, lastname From Employer
Where Employer.reports to =Employeeno.reports to

这只是一个例子。不要担心拼写错误和一切。

1 个答案:

答案 0 :(得分:2)

您需要将表格加入自身:

select e1.Employeeno,
  e1.lastname EmpLastName,
  e1.firstname empFirstName,
  e1.reportsto,
  e2.firstname MgrFirstName,
  e2.lastname MgrLastName
from employer e1
inner join employer e2
  on e1.reportsto = e2.employeeno

请参阅SQL Fiddle with Demo

如果您想查看所有员工,包括总裁,请将其更改为LEFT JOIN

select e1.Employeeno,
  e1.lastname EmpLastName,
  e1.firstname empFirstName,
  e1.reportsto,
  e2.firstname MgrFirstName,
  e2.lastname MgrLastName
from employer e1
left join employer e2
  on e1.reportsto = e2.employeeno

请参阅SQL Fiddle with Demo

如果您想使用更多描述性表别名,那么您可以使用以下内容:

from employer employee
left join employer manager
  on employee.reportsto = manager.employeeno