表Aid name pid
3 c 1
4 d 1
5 e 2
6 f 4
7 g 3
8 h 6
9 i 7
10 j 7
11 k 5
12 l 9
13 m 10
14 n 8
15 o 14表B只有id列,如何能效率得到root列, 如下id root
4 1
7 1
9 1
11 2
12 1
15 1
3 c 1
4 d 1
5 e 2
6 f 4
7 g 3
8 h 6
9 i 7
10 j 7
11 k 5
12 l 9
13 m 10
14 n 8
15 o 14表B只有id列,如何能效率得到root列, 如下id root
4 1
7 1
9 1
11 2
12 1
15 1
;with t(id,pid,topid)
as(
select id,pid,pid
from A
where not exists (select 1 from A A1 where A.pid=A1.id)
union all
select A.id,A.pid,t.topid
from A,t
where A.pid=t.id
)
select B.id,t.topid [root] from B,t where B.id=t.id;