我有两个表:第一个持有员工(任何职位的员工),第二个持有经理员工与身份证号码的关系。
我想写一个像
这样的查询1st field: name(employee),
2nd field: name(manager)
我该怎么做?
答案 0 :(得分:2)
不需要嵌套查询,只需使用标准连接:
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)
答案 1 :(得分:1)
你可以用一张桌子来做到这一点:
Employee
--------
EmployeeId int
Name varchar(50)
ManagerId int
ManagerId
指向同一表中经理的条目。 CEO将拥有null
的ManagerId。示例表定义:
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';