「已注销」 2022-02-17 16:04 采纳率: 100%
浏览 39
已结题

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

img


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

  • 写回答

2条回答 默认 最新

  • DarkAthena ORACLE应用及数据库设计方案咨询师 2022-02-17 17:30
    关注
    --测试数据
    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 2月26日
  • 已采纳回答 2月18日
  • 创建了问题 2月17日

悬赏问题

  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码