有一个sql的树形结构
uid name pid
 1 a 0
 2 b 1
 3 c 2
 4 d 3
 5 e 0
 6 f 5
 
如何给定一个Uid,,查询所有的父亲节点,
比如.给定uid=4
查询出.0,1,2,3
现在跟距
select uid
from t
start with uid=4
connect by prior pid=uid;
的方法 可以查出
 4   3
 3   2
 2   1
 1   0那请问如何可以加一条
 0    -

解决方案 »

  1.   

    select id, pid
      from t_test
     start with id = 4
    connect by prior pid = id
    union all
    select pid, null
      from t_test
     where connect_by_isleaf = 1
     start with id = 4
    connect by prior pid = id
      

  2.   

    with t as (select id,pid,connect_by_isleaf leaf
    from t_test
    start with id=4
    connect by prior pid=id)
    select id,pid from t
    union all
    select pid,null from t where leaf=1
      

  3.   


    create table t as
    select 1 u_id,'a' nm,0 pid from dual union all
    select 2,'b',1 from dual union all
    select 3,'c',2 from dual union all
    select 4,'d',3 from dual union all
    select 5,'e',0 from dual union all
    select 6,'f',5 from dual
    /
    select u_id,pid
    from t
    start with u_id=4
    connect by prior pid=u_id
    union all
    select pid,null
    from t
    where connect_by_isleaf=1
    start with u_id=4
    connect by prior pid=u_id;
          U_ID        PID
    ---------- ----------
             4          3
             3          2
             2          1
             1          0
             0
    --