2015-10-06 72 views
0

假設公司的層次結構是這樣的:甲骨文分層查詢選擇記錄

King 
-> John 
    -> Jack 
    -> Chris 
    -> Sean 
    -> April 
-> Jerry 
    -> Tom 

鑑於祖先例如Kingsubordinate,例如, Chris,是否可以在一個查詢中選擇路徑/King/John/Jack/Chris中的所有記錄?即查詢將返回4條記錄 - King, John, Jack and Chris

表結構: Employee_Name的Employee_ID MANAGER_ID

MANAGER_ID引用EMPLOYEE_ID

+1

是的,這是可能的。你應該從Chris'開始,選擇所有的父母。表格定義和樣本數據將會有所幫助。 [我想你可以從這裏開始...](http://stackoverflow.com/questions/2319284/sql-recursive-query-on-self-refrencing-table-oracle) – valex

回答

0
with t as 
(
    select 'King' as Employee_Name, 1 as Employee_ID, -1 as Manager_ID from dual union all 
    select 'John' as Employee_Name, 2 as Employee_ID, 1 as Manager_ID from dual union all 
    select 'Jack' as Employee_Name, 3 as Employee_ID, 2 as Manager_ID from dual union all 
    select 'Chris' as Employee_Name, 4 as Employee_ID, 3 as Manager_ID from dual union all 
    select 'Sean' as Employee_Name, 5 as Employee_ID, 3 as Manager_ID from dual union all 
    select 'April' as Employee_Name, 6 as Employee_ID, 2 as Manager_ID from dual union all 
    select 'Jerry' as Employee_Name, 7 as Employee_ID, 1 as Manager_ID from dual union all 
    select 'Tom' as Employee_Name, 8 as Employee_ID, 7 as Manager_ID from dual 
) 
select Employee_Name 
from t 
connect by prior Manager_ID = Employee_ID 
start with Employee_Name = 'Chris' 
order by level desc 
0

我不知道你的表結構是什麼。如果你將它作爲路徑存儲,那麼下面的內容應該可以工作。該查詢支持Chris的多條記錄。它會選擇所有的。

with test as 
    (
    select 1 id, '/King/John/Jack/Chris' str from dual union all 
    select 2 id, '/King/John/Jack/April' str from dual union all 
    select 3 id, '/King/John/Jack/Sean' str from dual union all 
    select 4 id, '/King/Jerry/Tom' str from dual 
) 
    select id, 
      str, 
     regexp_substr (str, '[^/]+', 1, rn) split, 
      rn 
    from test 
    cross 
    join (select rownum rn 
      from (select max (length (regexp_replace (str, '[^/]+'))) + 1 mx 
        from test 
       ) 
     connect by level <= mx 
     ) A 
    where regexp_substr (str, '[^/]+', 1, rn) is not null 
    and instr(str, 'Chris') > 0 
    order by id, rn 
; 

這裏是SQL小提琴爲例

Example in SQL Fiddle

訣竅是交叉連接創建用於主表的每一行多行。

ID STR SPLIT RN 
1 /King/John/Jack/Chris King 1 
1 /King/John/Jack/Chris John 2 
1 /King/John/Jack/Chris Jack 3 
1 /King/John/Jack/Chris Chris 4