简体   繁体   English

mysql join不返回所需的结果

[英]mysql join not returning required result

My data looks like the following,我的数据如下所示,

employeeId  ManagerId
 3            2
 4            2
 2            1
 5            1
 6            3

An employee has a manager and that manager will/could have a manager.员工有一位经理,而该经理将/可能有一位经理。 What i would like to do is get the manager of an employee and the manager of that manager should it be available.我想做的是让员工的经理和该经理的经理(如果可用)。

For eg For employee 6 the result will be 3 & 2. For employee 2 it will be 1.例如,对于员工 6,结果将为 3 & 2。对于员工 2,结果将为 1。

The key requirement here is that the query should return minimum one manager if available and max two levels and no higher.这里的关键要求是,如果可用,查询应该返回最少一个管理器,最多两个级别,不能更高。 The example given for employee 6 illustrates that.为员工 6 提供的示例说明了这一点。

Right now my query looks like,现在我的查询看起来像,

 select a.managerId firstManager,b.ManagerId secondManager
 from (
 select managerId from Results where employeeId = 6  ) a 
  join 
 (select managerId from Results where employeeId in (select managerId from  Results where employeeId = 6 ) )b ;

My query works for employee 6 but not for employee 2. dbfiddle我的查询适用于员工 6,但不适用于员工2。dbfiddle

You can try the below - with recursive cte: DEMO您可以尝试以下操作 - 使用递归 cte: DEMO

with RECURSIVE t as
(
select employeeid,managerid from Results where employeeid=6 
union all
SELECT e.employeeid,e.managerid from Results e inner join t t1 on e.employeeid = t1.managerid
) 
select * from t order by managerid desc limit 2

You can do a self join and you will get the results you require.您可以进行自连接,您将获得所需的结果。 dbfiddle

Select a.employeeId,
       a.ManagerId First_Manager, 
       b.ManagerId Second_Manager 
from Results a
left join Results b
on a.ManagerId = b.employeeId

Output:输出:

EmployeeId  First_Manager   Second_Manager
3   2   1
4   2   1
2   1   null
5   1   nul
6   3   2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM