I need to find the team total for the unilevel mlm tree I am having users table as this
+-------+-------+-----------+
| 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 |
+-------+-------+-----------+
and I have invoice_order table like this
+-------+-------+-----------+--------+
| 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 |
+-------+-------+-----------+--------+
Here I have to calculate the personal total and the team total of the Ids, example(tree):
sk001
|
|--sk002
| |--sk004
| | |--sk009
| | |--xy
| |
| |--sk005
|
|--sk003
for example : Team total of sk002
should contain the total purchase amount of an individual in the team (sk004,sk009,xy)
I have just tries something like this :
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
but I am not getting correct team total Is there any possibilities to use mysql procedure
You can use a CTE if you have MySQL 8+
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 to the fiddle