sql >> Base de Datos >  >> RDS >> Oracle

Encuentre el árbol completo desde la raíz dando cualquier nodo

Primero debe recorrer el árbol hacia arriba para obtener a todos los gerentes y luego recorrer hacia abajo para buscar a todos los empleados:

select level, employee_id, last_name, manager_id ,
       connect_by_root employee_id as root_id
   from employees
connect by prior employee_id = manager_id -- down the tree
start with manager_id in ( -- list up the tree
     select manager_id 
       from employees
     connect by employee_id = prior manager_id -- up the tree
     start with employee_id = 101
     )
;

Consulte http://www.sqlfiddle.com/#!4/d15e7/18

Editar:

Si el nodo dado también puede ser el nodo raíz, extienda la consulta para incluir el nodo dado en la lista de nodos principales:

Ejemplo de nodo no raíz:

select distinct employee_id, last_name, manager_id 
   from employees
connect by prior employee_id = manager_id -- down the tree
start with manager_id in ( -- list up the tree
     select manager_id 
       from employees
     connect by employee_id = prior manager_id -- up the tree
     start with employee_id = 101
     union 
     select manager_id -- in case we are the root node
       from employees
     where manager_id = 101
     )
;

Ejemplo de nodo raíz:

select distinct employee_id, last_name, manager_id 
   from employees
connect by prior employee_id = manager_id -- down the tree
start with manager_id in ( -- list up the tree
     select manager_id 
       from employees
     connect by employee_id = prior manager_id -- up the tree
     start with employee_id = 100
     union 
     select manager_id -- in case we are the root node
       from employees
     where manager_id = 100
     )
;

Violín en http://www.sqlfiddle.com/#!4/d15e7/32