sql >> Database teknologi >  >> RDS >> Oracle

Find hele træet fra roden, der giver en hvilken som helst knude

Du skal først krydse op i træet for at få alle ledere og derefter krydse ned for at hente alle medarbejdere:

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
     )
;

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

Rediger:

Hvis den givne node også kan være rodnoden, skal du udvide forespørgslen til at inkludere den givne node på listen over overordnede noder:

Eksempel på ikke-rodknude:

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
     )
;

Eksempel på rodnode:

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
     )
;

Fiddle på http://www.sqlfiddle.com/#!4/d15e7/32



  1. Bedste måde at installere hstore på flere skemaer i en Postgres-database?

  2. GROUP_CONCAT() Funktion i MySQL

  3. Hvordan kan jeg måle mysql-tid, tiden og/eller belastningen af ​​en sql-forespørgsel i php?

  4. Sammenligning af Galera Cluster Cloud-tilbud:Del 1 Amazon AWS