Trước tiên, bạn cần đi qua cây để tìm tất cả người quản lý, sau đó đi xuống để tìm nạp tất cả nhân viên:
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
)
;
Xem http://www.sqlfiddle.com/#!4/d15e7/18
Chỉnh sửa:
Nếu nút đã cho cũng có thể là nút gốc, hãy mở rộng truy vấn để đưa nút đã cho vào danh sách các nút mẹ:
Ví dụ cho nút không phải gốc:
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
)
;
Ví dụ cho nút gốc:
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 tại http://www.sqlfiddle.com/#!4/d15e7/32