【问题标题】:find the sum of parent-child in mysql在mysql中找到父子的总和
【发布时间】:2021-03-04 07:07:18
【问题描述】:
id  parent-id   total
139    0       -11000.00
140   139      -2000.00
141   140      3000.00
142   141       0.00
143   142      5000.00
144   143      0.00
145   144      0.00
147   145      0.00
148   147      0.00

这是我的桌子。这些值存储在临时表中。我需要找到父子总和。 预期输出

id  parent-id   total        sub-tot
139        0    -11000.00   -5000
140      139    -2000.00    6000
141      140    3000.00    8000
142      141    0.00       5000
143      142    5000.00    5000
144      143    0.00       0
145      144    0.00       0
147      145    0.00       0
148      147    0.00       0

我无法使用递归,因为我的数据存在于临时表中。有没有其他办法

【问题讨论】:

  • 这个“父子之和”是如何工作的?
  • 我已经给出了例如 id-139 sub-tot 的预期输出应该是(-11000-2000+3000+0+5000+0+0+0+0).@KIKOSoftware 和类似的子孩子,我已经给出了预期的输出。

标签: mysql sql sum parent-child recursive-query


【解决方案1】:

我无法使用递归,因为我的数据存在于临时表中。

例如,您可以在存储过程中使用静态表副本。

CREATE PROCEDURE get_subtotal ()
BEGIN

CREATE TABLE statictest SELECT * FROM temptest;

WITH RECURSIVE
cte AS ( SELECT id, 
                parent_id, 
                total, 
                0 subtotal, 
                id current_id, 
                NOT EXISTS ( SELECT NULL 
                             FROM statictest tt2 
                             WHERE tt2.parent_id = statictest.id ) done
         FROM statictest
         UNION ALL
         SELECT cte.id, 
                cte.parent_id, 
                cte.total, 
                cte.subtotal + tt1.total, 
                tt1.id,
                NOT EXISTS ( SELECT NULL 
                             FROM statictest tt2 
                             WHERE tt2.parent_id = tt1.id )
         FROM cte 
         JOIN statictest tt1 ON cte.current_id = tt1.parent_id )
SELECT id, parent_id, total, subtotal 
FROM cte
WHERE done
ORDER BY id;

DROP TABLE statictest;

END

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=8667bfeb06495f6f4dea7280b27a2a43

【讨论】:

  • 感谢队友,结果不是对父级金额求和
  • @yeshwant 如果您需要其他内容,请使用您自己的查询...我的回答主要告诉您如何解决临时表的问题...
  • @akia 是的,我试图从您的查询中理解并解决它。谢谢队友
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
相关资源
最近更新 更多