有一个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
查询出.1,2,3
另外..相依问下oracle不支持这样的临时表吗?sql可以的..select R_ID,U_ID into # from USER_INVITE where U_ID='xxx'
while @@rowcount>0
    insert # 
    select a.R_ID,a.U_ID 
    from tb a join # b
    on a.U_ID=b.R_ID and a.U_ID not in(select ID from #)select * from #

解决方案 »

  1.   


    select uid
    from t
    start with uid=4
    connect by prior pid=uid;
      

  2.   


    SQL> with t as(
      2       select 1 u_id,'a' nm,0 pid from dual union all
      3       select 2,'b',1 from dual union all
      4       select 3,'c',2 from dual union all
      5       select 4,'d',3 from dual union all
      6       select 5,'e',0 from dual union all
      7       select 6,'f',5 from dual
      8       )
      9  select u_id,pid
     10  from t
     11  start with u_id=4
     12  connect by prior pid=u_id
     13  /      U_ID        PID
    ---------- ----------
             4          3
             3          2
             2          1
             1          0
    关于emp树
      

  3.   


    --临时表,如果只是临时存数据的话,这样挺好:
    with cet as(
         select ...from ...
         )
    select ...
    from cte
     oracle CTE 简介
      

  4.   

    如果我想把0 0也弄出来呢.?
          U_ID        PID
    ---------- ----------
             4          3
             3          2
             2          1
             0          -