我有一个表,其中有employeeNumber
列和reportsTo
列,如您从屏幕快照中看到的那样。每个名称都会报告另一个名称。像employeeNumber 1165 reportsTo 1143
。
如何在结果中显示雇员的每个firstName
和lastName
以及他的“老板”的firstName
和lastName
?
希望您能理解我。
答案 0 :(得分:2)
您可以尝试以下方法:
SELECT e.firstName, e.lastName, b.firstName, b.lastName
FROM employees as e
LEFT JOIN employees as b on b.employeeNumber = e.reportsTo;
b.employeeNumber = e.reportsTo
上进行了加入,因此您将从雇员报告的employeeNumber中获得老板信息(例如,雇员1056向雇员1002报告,因此雇员数据为帕特森·玛丽,而他向雇员墨菲·黛安报告,她的老板)编辑:
在阅读关于SELF JOIN
的Hamza Haider答案(我之前在同一张桌子上进行连接的名称)后,我发现了另一个问题,答案看起来像您想要的一样,它将为您提供一些了解的信息SELF JOIN
的工作方式:What is SELF JOIN and when would you use it?
根据答案,这是另一种解决方案:
SELECT
e1.FirstName,
e1.LastName,
e2.FirstName as SupervisorFirstName,
e2.LastName as SupervisorLastName
FROM employee e1
LEFT OUTER JOIN employee e2 on e2.employeeNumber = e1.reportsTo
区别是LEFT OUTER JOIN
而不是LEFT JOIN
,但它们都是相同的(Are left outer joins and left joins the same?)
答案 1 :(得分:1)
尝试这个。它将仅返回那些具有reportTo值(而不是null值)的对象。
SELECT
e.firstName,
e.lastName,
r.firstName AS bossFirstName,
r.lastName AS bossLastName
FROM employees AS e
INNER JOIN employees AS r ON e.employeeNumber = r.reportsTo;
如果即使每个员工都没有reportTo值,也要查看它,则可以使用LEFT JOIN:
SELECT
e.firstName,
e.lastName,
r.firstName AS bossFirstName,
r.lastName AS bossLastName
FROM employees AS e
LEFT JOIN employees AS r ON e.employeeNumber = r.reportsTo;
答案 2 :(得分:0)
您需要使用自我加入。Self Join
select * from Employees AS Employees1 join Employees as Employees2 ON Employees1.employeeNumber = Employees2.reportsTo