简体   繁体   English

SELECT在单个表中具有一行的祖父级-SQL

[英]SELECT grand parent of a row with in a single table - SQL

I have a table with following hypothetical data: 我有一张包含以下假设数据的表:

ID | Name    | managerId
---|---------|-----------
1  | James   | 2
2  | Martin  | 4
3  | Huges   | 5
4  | Richard | NULL
5  | Kavin   | 4
6  | Rita    | 3

In the above table we have: 在上表中,我们有:

Richard is manager of Martin is manager of James. 理查德是马丁的经理,是詹姆斯的经理。

Richard is manager Kavin is manager of Huges is manager of Rita. 理查德是经理卡文是休斯的经理,丽塔是经理。

Now I have to select immediate manager and grand manager of an employee in this table. 现在,我必须在此表中选择员工的直属经理和大经理。 I mean if we start from Rita I have to select Huges (immediate manager) and Richard (grand manager). 我的意思是,如果我们从Rita开始,我必须选择Huges (直属经理)和Richard (大经理)。

How to do that. 怎么做。 I have no clue at all. 我一点都不知道。

EDIT : 编辑
There isn't any specific levels of managers. 没有特定级别的经理。 An Employee can have 'n' Number for managers in hierarchy where n ϵ {0,1,2,3.....} 对于层级为n的经理,雇员可以具有“ n”个数字{0,1,2,3 .....}

Because you only need two levels, this is quite feasible to do this with a self join, twice. 由于您只需要两个级别,因此通过两次自我连接来做到这一点是非常可行的。 Also, you probably want left join : 另外,您可能想要left join

select t.*, tm.name as managername, tmm.name as manager_managername
from t left join
     tm
     on t.managerId = tm.id left join
     tmm
     on tm.managerId = tmm.id;

You can add where t.name = 'Rita' . 您可以在where t.name = 'Rita'添加where t.name = 'Rita'

If you have to do this up to any level, then you should definitely review this question . 如果您必须执行任何级别的操作,则绝对应该查看此问题 The short answer is that you probably need another data structure to handle this type of query in MySQL. 简短的答案是,您可能需要另一个数据结构来处理MySQL中的这种类型的查询。

EDIT: 编辑:

The following answer works only for a specific level of parents (as question was asking before the change). 以下答案仅适用于特定级别的父母(因为问题是在变更之前提出的)。 I am sure that for N levels it needs a completely different approach. 我确信对于N级,它需要一种完全不同的方法。

You can use this. 您可以使用它。 It's going up to three levels of managers and finds all employees who have at least 2 levels of managers. 它上升到三个级别的经理,并找到拥有至少两个级别的经理的所有员工。

SELECT aa.Name AS employee, bb.Name AS parent_manager, cc.Name AS grandparent_manager, dd.Name AS grand_grandparent_manager
FROM t1 AS aa
INNER JOIN t1 AS bb
ON aa.managerId = bb.ID
INNER JOIN t1 AS cc
ON bb.managerId = cc.ID
LEFT JOIN t1 AS dd
ON cc.managerId = dd.ID

And this is if you want the managers for a specific employee. 这是您是否要为特定雇员提供经理。

SELECT aa.Name AS employee, bb.Name AS parent_manager, cc.Name AS grandparent_manager, dd.Name AS grand_grandparent_manager
FROM t1 AS aa
INNER JOIN t1 AS bb
ON aa.managerId = bb.ID
INNER JOIN t1 AS cc
ON bb.managerId = cc.ID
LEFT JOIN t1 AS dd
ON cc.managerId = dd.ID
WHERE aa.Name = 'Rita'

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

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