-1

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

4

3 回答 3

2

将表与自身连接(注意使用别名来消除两者的歧义):

SELECT e.empName AS employeeName, 
    m.empName AS managerName
FROM Employee e
INNER JOIN Employee m ON e.managerId = m.empId
于 2012-11-02T10:31:01.243 回答
1

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

SELECT
    Employee.empName AS employeeName,
    Manager.empName AS managerName
FROM Employee
JOIN Employee AS Manager
ON Employee.managerId = Manager.empId
于 2012-11-02T10:31:01.913 回答
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小提琴为此

于 2012-11-02T10:37:02.147 回答