所以我需要创建一个列出每位员工经理的表。我知道我需要将经理ID与员工ID联系起来,但我不知道该怎么做
create table employee
(EmpID int,
name varchar (50),
title varchar (50),
managerID int,
salary int
);
执行命令时
select * from employee;
应该给出
EmpID name title managerID
----------------------------------------------
'101', 'Robert Jones', 'Sales Person', '102'
'102', 'Liz Farnandezs', 'Sales Manager','106'
'103', 'Mathew Richards','Sales Person', '102'
'104', 'Ethan Lubatkin', 'Sales Person', '105'
'105', 'Stuart Little', 'Store Manager', NULL
'106','Samantha Porter', 'Manager', NULL
我还是SQL的新手,所以任何可以帮我解决这个问题的东西都会很棒。
我需要一个看起来像这样的结果
EmpID name manager managerID
----------------------------------------------
'101', 'Robert Jones', 'Liz Farnandezs', '102'
'102', 'Liz Farnandezs', 'Samantha Porter','106'
'103', 'Mathew Richards','Liz Farnandezs', '102'
'104', 'Ethan Lubatkin', 'Stuart Little', '105'
'105', 'Stuart Little', NULL, NULL
'106','Samantha Porter', NULL, NULL
答案 0 :(得分:1)
您不需要额外的表,您可以在此表中获得所有必需的信息。
您只需要使用join(同一个表的两个实例,一个用于员工,一个用于经理)以获取经理的详细信息:
SELECT emps.empID, emps.name, managers.name as manager,
managers.empID as managerID
FROM employee as emps LEFT JOIN employee as managers
ON emps.managerID = managers.empID
答案 1 :(得分:0)
你所需要的就是这样,你LEFT JOIN
同一张桌子,让雇员和他的直接经理在同一行:
SELECT
e1.empID
, e1.name
, e2.name as Manager
, e2.empID as ManagerID
FROM employee e1
LEFT JOIN employee e2 ON e1.managerID = e2.empID