简体   繁体   English

求mysql中的父子之和

[英]find the sum of parent-child in mysql

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

This is my table.这是我的桌子。 the values is stored in temporary table.I need find the parent child sum.这些值存储在临时表中。我需要找到父子总和。 expected output预计 output

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

i couldn't use recursive as my data is present in temp table.我不能使用递归,因为我的数据存在于临时表中。 is there any other way有没有其他方法

i couldn't use recursive as my data is present in temp table.我不能使用递归,因为我的数据存在于临时表中。

You may use static table copy in stored procedure, for example.例如,您可以在存储过程中使用 static 表副本。

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 https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=8667bfeb06495f6f4dea7280b27a2a43

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM