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
查询效果