2014-09-01 12 views
7

Ho un albero binario presentato in uno SQL Server 2014 tabella:Binary Search Query utilizzando 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) 

Per ottenere lo scorso id sinistra e ultimo id destra Sto usando interrogazione CTE:

; 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 
; 

e

; 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 
; 

Sta funzionando bene. In questo modo posso avere l'ultima UserID nella parte di sinistra o di destra per root (per ParentUserID == 1)

ho bisogno di modificare la query CTE per ottenere lo stesso risultato, ma per specifiche ParentUserID cui voglio passare come parametro @ParentUserID.

Come raggiungere questo obiettivo?

risposta

2

Basta cambiare questa linea in ogni CTE:

from Table1 where ParentUserID is null 

a:

from Table1 where ParentUserID = @ParentId 
+1

sarebbe aiutare a spiegare agli altri perché che funziona piuttosto che la versione originale? –

+0

Ho provato, non funziona correttamente. Se non ho nel valore "Right" della tabella, la query mi restituisce LastRight per quella posizione. –

Problemi correlati