我想以这种格式输出:
e.EE_id e.FNAME e.LNAME SUPer_id s.FNAME s.LNAME
--- --------- -------------- --- ------------- -------------------
1 Ziqiao Li
2 Charlie Li 1 Ziqiao Li
3 George Pee 2 Charlie Li
4 Jason Dee 2 Charlie Li
5 Petey Wee 2 Charlie Li
从此表创建:我需要在显示主键名称的外键名称值时显示相同结果中的主键和外键。
Create table Employees(
ee_id integer,
fname varchar(20),
lname varchar(20),
super_id integer,
Constraint emp_Pk Primary Key (ee_id),
Constraint emp_Fk Foreign Key (super_id) references employees (ee_id)
);
INSERT INTO Employees VALUES(1,'Charlie','Li',null);
INSERT INTO Employees VALUES(2,'Ziqiao','Lee',1);
INSERT INTO Employees VALUES(3,'George','Pee',2);
INSERT INTO Employees VALUES(4,'Jason','Dee',2);
INSERT INTO Employees VALUES(5,'Petey','Wee',2);
Select ee_id, fname, lname, super_id from employees;
ee_id fname lname super_id
---------- ---------- ---------- ----------
1 Charlie Li
2 Ziqiao Lee 1
3 George Pee 2
4 Jason Dee 2
5 Petey Wee 2
我是否需要创建视图?
答案 0 :(得分:1)
只需将表格加入自身:
select e1.ee_id
e1.fname EmployeeFirstName,
e1.lname EmployeeLastName,
e1.super_id,
e2.fname SuperFirstName,
e2.lname SuperLastName
from Employees e1
left join Employees e2 on e1.super_id = e2.ee_id
第一次提及(e1
)将获得员工的数据,第二次提交(e2
)将为主管提供数据。
LEFT JOIN
将确保没有主管(ee_id = 1
)的员工将出现在结果中。
答案 1 :(得分:1)
您需要JOIN
:
Select e1.ee_id, e1.fname, e1.lname, e1.super_id, e2.fname AS Super_fname, e2.lname AS Superlname
from employees e1
left join employees e2
ON e1.super_id = e2.ee_id