select a.a,a.aname,b.a aroot,b.aname arootname
from tablename a,tablename b where a.afather = b.a
union
select c.a,c.aname,null aroot,null arootname from tablename c where c.afather is null;
create table test (
a varchar(10),
aname varchar(10),
afather varchar(10)
)
insert into test values('1','a','');
insert into test values('2','b','3');
insert into test values('3','c','5');
insert into test values('4','d','6');
insert into test values('5','e','1');
insert into test values('6','f','5');
commit;
select * from test
create or replace function get_root(pa in varchar2) return varchar2 as
cursor cur_b(p in varchar2) is
select a, aname, afather from test where a = p;
t test%rowtype;
a varchar2(10);
b varchar2(10);
begin
open cur_b(pa);
fetch cur_b
into t;
a := t.afather;
b := t.a;
close cur_b;
if a is null then --假设根节点的afather为空
return b;
else
return get_root(a);
end if;
end get_root;
select a.a, a.aname, c.af, c.an
from test a,
(select b.a aa, a.a af, a.aname an
from test a, (select a, get_root(a) id from test) b
where a.a = b.id) c
where a.a = c.aa
insert into tablename(a,aname,afather) values('1','1name','')
insert into tablename(a,aname,afather) values('11','11name','1')
insert into tablename(a,aname,afather) values('2','2name','1')
insert into tablename(a,aname,afather) values('12','12name','2')