您将需要一个 UNION,我建议删除相应级别的条目重复项。此外,如果您打算像在 Web 应用程序中一样向用户展示,则无需包含“NULL”值......
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 到下一个级别,否则,您将错过您尝试检索的级别的可能项目,但其他项目应保留为 INNER JOIN。
如果您正在处理产品,我认为如果不是经过 4 层深他们就找不到东西,那就是一个更大的问题 :)