我有这样的结构:
<Unit>
<SubUnit1>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnit1/>
<SubUnit2>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnit2/>
...
<SubUnitN>
<SubSubUnit1/>
<SubSubUnit2/>
...
<SubSubUnitN/>
</SubUnitN/>
</Unit>
该结构有 3 个层次:主单元、子单元和子子单元。
我想按 UnitId 选择所有孩子。
如果我按单位搜索,我必须得到所有的树。
如果我按 SubUnit1 搜索,我必须得到 SubUnit1 和 SubUnit1 的所有子项。
如果我搜索 SubSubUnit2,我必须得到它自己。
这是我的尝试:
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
我用了 3 个联合词,效果不好,但很管用。案例结构将有N个级别,我如何获得正确的结果?