Mam strukturę tak:
Jak zdobyć wszystkie dzieci rodziców, a potem ich dzieci korzystających rekursji w zapytaniu
<Unit>
<SubUnit1>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnit1/>
<SubUnit2>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnit2/>
...
<SubUnitN>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnitN/>
</Unit>
Struktura ta ma 3 poziomy: Main Unit, podjednostek i SubSubUnits.
Chcę wybrać wszystkie dzieci według UnitId.
Jeśli przeszukuję według jednostki, muszę pobrać całe drzewo.
Jeśli wyszukuję według SubUnit1, muszę pobrać SubUnit1 i wszystkie podrzędne dla dzieci SubUnit1.
Jeśli wyszukuję SubSubUnit2, muszę się sam.
Oto moja próba:
with a(id, parentid, name)
as (
select id, parentId, name
from customer a
where parentId is null
union all
select a.id, a.parentid, a.Name
from customer
inner join a on customer.parentId = customer.id
)
select parentid, id, name
from customer pod
where pod.parentid in (
select id
from customer grbs
where grbs.parentid in (
select id
from customer t
where t.parentid = @UnitId
))
union
select parentid, id, name
from customer grbs
where grbs.parentid in (
select id
from customer t
where t.parentid = @UnitId
)
union
select parentid, id, name
from customer c
where c.Id = @UnitId
order by parentid, id
używam 3 Unię słowa, to nie jest dobrze, ale to działa. Struktura przypadku będzie miała N poziomów, w jaki sposób muszę uzyskać poprawny wynik?
Spójrz na to odpowiedź: http://stackoverflow.com/questions/317322/optimized-sql-for-tree-structures – twoleggedhorse