如何获取单级传销树的团队总数

how to take team total for unilevel mlm tree

我需要找到单级传销树的团队总数 我有这样的用户 table

+-------+-------+-----------+
| id    | fname | parent_id |
+=======+=======+===========+
| sk001 | aa    | null      |
+-------+-------+-----------+
| sk002 | ss    | ssk001    |
+-------+-------+-----------+
| sk003 | dd    | sk001     |
+-------+-------+-----------+
| sk004 | ff    | sk002     |
+-------+-------+-----------+
| sk005 | gg    | sk002     |
+-------+-------+-----------+
| sk006 | hh    | sk005     |
+-------+-------+-----------+
| sk007 | jj    | sk006     |
+-------+-------+-----------+
| sk008 | kk    | sk006     |
+-------+-------+-----------+
| sk009 | ll    | sk004     |
+-------+-------+-----------+
| sk010 | mm    | sk005     |
+-------+-------+-----------+

我有 invoice_order table 这样的

+-------+-------+-----------+--------+
| id    | fname | parent_id | amount |
+=======+=======+===========+========+
| sk001 | aa    | null      | 100    |
+-------+-------+-----------+--------+
| sk002 | ss    | ssk001    | 400    |
+-------+-------+-----------+--------+
| sk002 | dd    | sk001     | 225    |
+-------+-------+-----------+--------+
| sk004 | ff    | sk002     | 50     |
+-------+-------+-----------+--------+
| sk005 | gg    | sk002     | 59     |
+-------+-------+-----------+--------+
| sk006 | hh    | sk005     | 77     |
+-------+-------+-----------+--------+
| sk007 | jj    | sk006     | 89     |
+-------+-------+-----------+--------+
| sk004 | ff    | sk002     | 87     |
+-------+-------+-----------+--------+
| sk009 | ll    | sk004     | 45     |
+-------+-------+-----------+--------+
| sk010 | mm    | sk005     | 56     |
+-------+-------+-----------+--------+

这里我要计算个人总计和团队总计的Ids, 示例(树):

             sk001 
                |
                |--sk002
                |     |--sk004
                |     |    |--sk009
                |     |    |--xy
                |     |
                |     |--sk005
                |
                |--sk003  

例如:团队合计sk002应该包含团队中个人的总购买金额(sk004,sk009,xy)

我刚刚尝试过这样的事情:

SELECT  (SUM(amount))/2 as indteamtotal 
                                          from    (SELECT * from invoice_order
                                                   order by id, parent_id) products_sorted,
                                                  (SELECT @pv := 'sk002') initialisation
                                          where   find_in_set(parent_id, @pv) > 0
                                          and     length(@pv := concat(@pv, ',', id)) order by parent_id asc

但我没有得到正确的团队总数 是否有可能使用 mysql 程序

如果你有 MySQL 8+

,你可以使用 CTE
with recursive tree as (
 select id from invoice_order where id = 'sk002'
 union
 select i.id from invoice_order i join tree on tree.id = i.parent_id
)  
select sum(amount) from invoice_order where id in (select id from tree);

Link 到 fiddle