1. 程式人生 > >資料庫處理二叉樹的一個例項

資料庫處理二叉樹的一個例項

這是帖子原文

感覺超難SQL問題 單表查詢連線起點末點

表:
起點 末點
1      2
2      3
3      4
4      5 
a      b 
等等

想要查詢出來的結構:
(1)起末點連線:
起點 末點 起點 末點 起點 末點 起點 末點
1       2       2      3      3       4       4      5
(2)除去以上連線的點以外還有獨立的點:
起點 末點
a       b

可以用多條SQL查詢,只要查詢出來的結果拼湊起來沒有重複即可,

很顯然,常規手段處理有難度,仔細分析問題  ,其實只是一棵二叉樹,基於二叉樹的處理方式,很容易實現,具體如下:

--設定測試資料
create table #abc(s varchar(10),e varchar(10),Path varchar(100))
go
insert into #abc(s,e)
select 1,2 union
select 2,3 union 
select 3,4 union
select 4,5 union
select 'a','b'

update #abc set [Path]=null
--設定根節點
update #abc
set Path=s+','+e+'->'
where s not in(select e from #abc)

while @@rowcount>0
begin
--迴圈處理兒子節點
  update #abc
  set Path=t2.Path+t1.s+','+t1.e+'->'
  from #abc t1
    join(select * from #abc) t2 on t1.s=t2.e
  where t1.Path is null
end
--選擇唯一路徑
select path from #abc where e not in(select s from #abc)
--路徑結果如下
path                                                                                                 
---------------------------------------------------------------------------------------------------- 
1,2->2,3->3,4->4,5->
a,b->

完美解決使用者要求