Ich habe Struktur wie folgt aus:
Wie alle Kinder eines Elternteils zu bekommen und ihre Kinder dann in Abfrage mit Rekursion
<Unit>
<SubUnit1>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnit1/>
<SubUnit2>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnit2/>
...
<SubUnitN>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnitN/>
</Unit>
Diese Struktur verfügt über 3 Ebenen: Hauptgerät, Untereinheitenund SubSubUnits.
Ich möchte alle Kinder von UnitId auswählen.
Wenn ich nach Einheit suche, muss ich alle Baum bekommen.
Wenn ich nach SubUnit1 suche, muss ich SubUnit1 und alle Kinder von SubUnit1 bekommen.
Wenn ich SubSubUnit2 suche, muss ich mich selbst holen.
Hier ist mein Versuch:
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
Ich benutze 3 gewerkschafts Worten, es ist nicht gut, aber es funktioniert. Fallstruktur wird N Ebenen haben, wie muss ich das richtige Ergebnis bekommen?
Werfen Sie einen Blick auf diese Antwort: http://stackoverflow.com/questions/317322/optimized-sql-for-tree-structures – twoleggedhorse