【问题标题】:Mysql sum balance recursively for all the hierarchyMysql总和余额递归所有层次结构
【发布时间】:2021-06-14 12:49:27
【问题描述】:

我有一个这样的用户表

userId username balance parentId parentInfo
1 john 1000 0 0,
2 roy 2000 1 1,0,
3 James 2000 1 1,0,
4 Allen 5000 2 2,1,0,
5 Nell 4000 2 2,1,0,
6 Andy 1500 5 5,2,1,0,

我想列出所有用户及其所有下线的余额总和 像这样

userId username balance parentId downlineBalance
1 john 1000 0 14500
2 roy 2000 1 10500
3 James 2000 1 0
4 Allen 5000 2 0
5 Nell 4000 2 1500
6 Andy 1500 5 0

【问题讨论】:

  • 为每个 downlineBalance 值添加详细说明。特别是对于 userId 2 - 也许它必须是 10500?
  • 抱歉编辑了问题下线余额是指直接孩子、授予孩子、曾孙等的余额之和,如果userId 2下线余额将为10500)
  • 对于 userId 2 的下线余额将为 10500,这是 userId 4、5、6 (5000+4000+1500) 的余额之和,其中 userid 4 和 5 是直接子代,而 userid 6 是其子代孩子

标签: mysql join inner-join union recursive-query


【解决方案1】:
WITH RECURSIVE
cte AS ( SELECT *, parentId upperId
         FROM test
       UNION ALL
         SELECT cte.userId, cte.username, cte.balance, cte.parentId, test.parentId
         FROM test
         JOIN cte ON test.userId = cte.upperId
       )
SELECT test.*, COALESCE(SUM(cte.balance), 0) downlineBalance
FROM test
LEFT JOIN cte ON test.userId = cte.upperId
GROUP BY test.userId

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=506baa4e100d2eb76de4321343c9ba3d

【讨论】:

    猜你喜欢
    • 2013-02-09
    • 2013-11-22
    • 2017-02-04
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多