如何在单个选择查询中从单个表中选择两个相同的列

时间:2012-11-02 10:28:34

标签: mysql sql

我有一个名为Employee的表,其列为empId,empName,managerId。这里经理是一名员工。如何从上表中获取员工姓名和经理姓名。

3 个答案:

答案 0 :(得分:2)

自己加入表格(注意使用别名来消除两者的歧义):

SELECT e.empName AS employeeName, 
    m.empName AS managerName
FROM Employee e
INNER JOIN Employee m ON e.managerId = m.empId

答案 1 :(得分:1)

尝试使用别名将表连接到自身:

SELECT
    Employee.empName AS employeeName,
    Manager.empName AS managerName
FROM Employee
JOIN Employee AS Manager
ON Employee.managerId = Manager.empId

答案 2 :(得分:1)

create table employee
 (
   empid int , 
   empName nvarchar(500),
   mgrid int 

 )

insert into employee select 1,'ra',0 
insert into employee select 2,'ma',1

获取经理姓名的子查询

select *
 ,(select empName  from employee as e where oe.mgrid=e.empid) as managername
from employee as oe

SELECT
    employee.empName AS employeeName,
    Manager.empName AS managerName
FROM employee
JOIN employee AS Manager
ON employee.mgrid = Manager.empId

sql fiddle for this