我有 2 个表:第 1 个保存员工(任何职位的员工),第 2 个保存带有 ID 号的经理员工关系。
我想写一个查询
1st field: name(employee),
2nd field: name(manager)
我怎样才能做到这一点?
我有 2 个表:第 1 个保存员工(任何职位的员工),第 2 个保存带有 ID 号的经理员工关系。
我想写一个查询
1st field: name(employee),
2nd field: name(manager)
我怎样才能做到这一点?
不需要嵌套查询,只需使用标准连接:
select e.*, m.*
from
employee e
left join employee_managers em
on e.id = em.emp_id
left join employee m
on m.id = em.man_id
每行将包含所有字段employee
(如果一个员工有多个关联的经理,可能有几行)和他对应经理的所有字段(或者NULL
如果员工没有经理,则为 s)。
你可以用一张桌子做到这一点:
Employee
--------
EmployeeId int
Name varchar(50)
ManagerId int
ManagerId
指向同一张表中经理的条目。CEO 的 ManagerId 为null
。示例表定义:
create table Employees (
EmployeeId int auto_increment primary key
, Name varchar(50)
, ManagerId int
, foreign key (ManagerId) references Employees(EmployeeId)
);
使用一些示例数据:
insert into Employees (Name) select 'The Chief';
insert into Employees (Name, ManagerId) select 'Grunt 1',
(select EmployeeId from Employees where Name = 'The Chief');
insert into Employees (Name, ManagerId) select 'Grunt 2',
(select EmployeeId from Employees where Name = 'The Chief');
insert into Employees (Name, ManagerId) select 'Secretary',
(select EmployeeId from Employees where Name = 'The Chief');
要查找第二个 Grunt 经理的姓名,您可以查询如下:
select mgr.Name
from Employees mgr
inner join Employees grunt
on grunt.managerid = mgr.employeeid
where grunt.name = 'Grunt 2';