簡體   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

這是我的桌子。 這些值存儲在臨時表中。我需要找到父子總和。 預計 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

我不能使用遞歸,因為我的數據存在於臨時表中。 有沒有其他方法

我不能使用遞歸,因為我的數據存在於臨時表中。

例如,您可以在存儲過程中使用 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM