php - Finding Top Parent (Recursive) -
product table:
id | id_parent | margin ------------------------ 1 | null | 10 2 | 1 | 20 3 | null | 15 4 | 2 | 10 5 | 4 | 25
from data above, how margin total of product tree (id: 5)? doesn't have fixed depth, dynamic.
i achieve iteration php (recursive mysqli_query), consumes huge hosting memory (error 508).
here php function:
function get_margintotal($product) { global $link; $query = "select id_parent, margin `products` id = ".$product['id_parent']; if (!$temp_products = mysqli_query($link, $query)) { die(json_encode(array("errmsg" => "selecting supplier's margin."))); } $temp_product = mysqli_fetch_assoc($temp_products); $temp_product['margin'] = $product['margin'] + $temp_product['margin']; if (isset($temp_product['id_parent'])) { return get_margintotal($temp_product); } else { return $temp_product['margin']; } }
so i'm wondering if dynamic iteration can done in mysql or how optimise function decrease server memory usage?
thank you.
mysql solution using recursion variables.
create table `finding_top_parent_recursive_46170847` ( `id` int(11) unsigned not null auto_increment, `id_parent` int(11) default null, `margin` int(11) default null, primary key (`id`) ) engine=innodb auto_increment=6 default charset=utf8; insert `finding_top_parent_recursive_46170847` (`id`, `id_parent`, `margin`) values (1, null, 10), (2, 1, 20), (3, null, 15), (4, 2, 10), (5, 4, 25); -- set seed leaf id set @id = 5 ; select sum(margin) margin ( -- include seed select id, margin finding_top_parent_recursive_46170847 products id = @id union -- parents select @id := ( select id_parent finding_top_parent_recursive_46170847 products id = @id ) id, ( select margin finding_top_parent_recursive_46170847 products id = @id ) margin finding_top_parent_recursive_46170847 products @id not null ) margins -- results margin 65
ideas recursive mysql results from
https://www.google.com.au/search?q=mysql+recursive+left+join
https://dba.stackexchange.com/questions/46127/recursive-self-joins
Comments
Post a Comment