你需要一个联合国构想,我建议删除各自层次的条目重复。 此外,如果你打算像在网络上那样向用户提供,就不需要列入“联合国扫盲十年”的价值。
select L1.Category_ID,
L1.name,
"1" as HierarchyLevel,
count( L2.Category_ID ) as NextLevelCount
from Category L1
LEFT JOIN Category L2
on L1.Category_ID = L2.Parent
where L1.name = "ELECTRONICS"
group by L1.Category_ID
UNION
select L2.Category_ID,
L2.name,
"2" as HierarchyLevel,
count( L3.Category_ID ) as NextLevelCount
from Category L1
JOIN Category L2
on L1.Category_ID = L2.Parent
LEFT JOIN Category L3
on L2.Category_ID = L3.Parent
where L1.name = "ELECTRONICS"
group by L2.Category_ID
UNION
select L3.Category_ID,
L3.name,
"3" as HierarchyLevel,
count( L4.Category_ID ) as NextLevelCount
from Category L1
JOIN Category L2
on L1.Category_ID = L2.Parent
JOIN Category L3
on L2.Category_ID = L3.Parent
LEFT JOIN Category L4
on L3.Category_ID = L4.Parent
where L1.name = "ELECTRONICS"
group by L3.Category_ID
UNION
select L4.Category_ID,
L4.name,
"4" as HierarchyLevel,
1 as NextLevelCount
from Category L1
JOIN Category L2
on L1.Category_ID = L2.Parent
JOIN Category L3
on L2.Category_ID = L3.Parent
JOIN Category L4
on L3.Category_ID = L4.Parent
where L1.name = "ELECTRONICS"
这显然是固定到4级的,但会将它们合并为单一名单,但不会重复你提出的内容。 我也只是为了参考目的而打上等级。 为了达到每个级别,你必须做一个LEFT JOIN到下一级别,否则,你就会在你试图检索的级别上错过可能的项目,但其他情况下,SHOULD仍然是INNER JOIN。
如果你处理产品,我想,如果在四级之后,他们就会发现一些东西,就会有一个更大的问题: