mysql 树状图数据递归。升级版问题

img


mysql 树状图数据递归。升级版问题
可以的话直接上SQL噢,我知道可以用代码逻辑解决

--测试数据
create table test_20220217 
(id int,name VARCHAR(2),p_id int,money int);
insert into test_20220217 values(1,'A',-1,10);
insert into test_20220217 values(2,'B',1,15);
insert into test_20220217 values(3,'C',1,12);
insert into test_20220217 values(4,'D',2,11);
insert into test_20220217 values(5,'E',2,13);
insert into test_20220217 values(6,'F',3,14);
insert into test_20220217 values(7,'G',4,20);
insert into test_20220217 values(8,'H',4,31);
insert into test_20220217 values(9,'I',5,55);

--查询
WITH RECURSIVE  cte as (select t.*,1 lvl,cast(null as  int) third_node from test_20220217 t where id=1
union all 
select t.*,lvl+1,case when lvl+1=3 then t.id when lvl+1>3 then cte.id end  from test_20220217 t,cte where cte.id=t.p_id
)
select third_node,sum(money) from cte where third_node is not null group by third_node

查询效果

img

如果你是5.7及其以下的版本,可以采取多加字段的方式去规避递归,加一个层级字段,以及id的全路径,比如你的D数据,层级是2,全路径则是1,2,4
这样你的需求直接变成层级=3,查子节点也就是变成全路径like,用空间去换时间
mysql8 则支持with as的写法,但是层级这个估计也还是不好处理