我有这样的声明:
select * from category a
inner join category b on a.row=b.relatedRow
inner join category c on b.row=c.relatedRow where a.row=?
我想像这样获得“级别”的数量:
如果a有行,level=1,如果b有行,level=2,如果c 有行,level=3。
我该怎么做?
示例
row, relatedRow
1,null
2,1
3,2
4,3
5,2
6,5
因此,1 与任何行都不相关,2 与 1 相关,3 与 2 相关,依此类推...
如果 row=1,则级别 1 存在,因为 1 存在
级别 2 存在,因为 2 与 1 相关
级别 3 存在,因为 3 和 5 与 2 相关
级别 4 存在,因为 6 与 5 相关,4 与 3 相关
因此这棵树下降了 4 层。
最佳答案
尝试一些类似的事情:
select
sum(case when not b.relatedRow is null then 1 else 0 end) as level1_total
sum(case when not c.relatedRow is null then 1 else 0 end) as level2_total
from category a
left join category b on a.row=b.relatedRow
left join category c on b.row=c.relatedRow where a.row=?
当然,您可以修改case
中的条件以适合您对有行的定义
关于如果表中存在行,MySQL 将创建一个总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36226683/