2013-01-08 15 views
2

我提供這裏一個例子,讓大家明白我真正需要的: 我有一個表是這樣的:需要將兩列的數據組合成SQL中的一列嗎?

Name          Null? Type 
----------------------------------------- -------- -------------- 
Child_ID            NUMBER(10) 
Father_ID            NUMBER(10) 

值是:

Child_ID  Father_ID 
----------   ---------- 
     2   1 
     4   1 
     3   2 
     5   3 

現在我想的分層信息父親ID 1.對於我已經寫了一個查詢和正在提供我確切的輸出:

**select * from child 
start with father_id=1 
connect by prior child_id = father_id;** 

O/P:

 Child_ID  Father_ID 
----------   ---------- 
     2   1 
     3   2 
     5   3 
     4   1 

現在我想的O/P應該是這樣的:

ID 
----- 
1 
2 
3 
4 
5 

我可以通過工會鍵得到它很容易,但我不希望使用。 有沒有其他辦法可以得到這個? 在此先感謝。

+0

你想從表子和父ID的不同列表,但不想使用UNION?請解釋你爲什麼不想使用最簡單和最明顯的方法。 –

+0

是的,你是對的,但我只想知道是否有其他方法可以得到這個。 – sujoy

+0

兩個我能想到的,一個是SELECT DISTINCT child_id到一個臨時表中,然後將parent_id合併到同一個表中。第二個是使用PL/SQL編寫聯合。儘管如此,它們也不會像聯盟那麼快或有效。數據庫很少有很多方法可以做同樣的事情。 –

回答

0

這是一個有點混亂,但你可以這樣做:

select distinct case when l=1 then child_id else father_id end id 
from 
    (select child_id, father_id 
    from child 
    start with father_id=1 connect by prior child_id=father_id) child 
    cross join (select level l from dual connect by level < 3) 
order by id 
; 
相關問題