日期:2014-05-18  浏览次数:20442 次

一遇到递归就头大, 这个怎么效率解决?
表A
SQL code

id    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列, 如下
SQL code

id    root
4    1
7    1
9    1
11    2
12    1
15    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 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;