表A
- SQL code
id name pid3 c 14 d 15 e 26 f 47 g 38 h 69 i 710 j 711 k 512 l 913 m 1014 n 815 o 14
表B只有id列,如何能效率得到root列, 如下
- SQL code
id root4 17 19 111 212 115 1
------解决方案--------------------
- SQL code
;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 allselect 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;