2014-09-01 21 views
7

mam binarne drzewo przedstawione w SQL Server 2014 tabela:Binary Search Query za pomocą SQL

UserID ParentUserID Position 
---------------------------- 
1  Null   Null  <-- ROOT 
2  1   Left 
3  1   Right <-- Last Right for ID=1 (CTE query return 3) 
4  2   Left 
5  4   Left 
6  5   Left 
7  6   Left  <-- Last Left for ID=1 (CTE query return 6) 

Aby uzyskać ostatni lewy id i ostatni prawy id Używam CTE zapytanie:

; with left_hand_recurse as 
(
     select UserID 
     ,  ParentUserID 
     ,  1 as depth 
     from Table1 where ParentUserID is null 
     union all 
     select child.UserID 
     ,  child.ParentUserID 
     ,  parent.depth + 1 
     from left_hand_recurse parent 
     join Table1 child 
     on  parent.UserID = child.ParentUserID 
       and position = 'Left' 
) 
select top 1 * 
from left_hand_recurse 
order by 
     depth desc 
; 

i

; with right_hand_recurse as 
(
     select UserID 
     ,  ParentUserID 
     ,  1 as depth 
     from Table1 where ParentUserID is null 
     union all 
     select child.UserID 
     ,  child.ParentUserID 
     ,  parent.depth + 1 
     from right_hand_recurse parent 
     join Table1 child 
     on  parent.UserID = child.ParentUserID 
       and position = 'Right' 
) 
select top 1 * 
from right_hand_recurse 
order by 
     depth desc 
; 

Działa poprawnie. W ten sposób mogę dostać ostatnią UserID w lewej lub prawej stronie na root (dla ParentUserID == 1)

muszę zmodyfikować kwerendę CTE, aby uzyskać ten sam wynik, ale dla konkretnej ParentUserID które chcę przekazać jako parametr @ParentUserID.

Jak osiągnąć ten cel?

Odpowiedz

2

Wystarczy zmienić tę linię w każdym CTE:

from Table1 where ParentUserID is null 

do:

from Table1 where ParentUserID = @ParentId 
+1

pomogłoby wyjaśnić innym, dlaczego to działa zamiast oryginalnej wersji? –

+0

Próbowałem, nie działa poprawnie. Jeśli nie mam w tabeli wartości "Right", zapytanie zwróci mi LastRight dla tej pozycji. –