Get sum from nodes tree

LTREE

You are almost on the right track. You almost stumbled upon the ‘LTREE’ system of storing hierachial data in a database. You just need to make a slight modidification. that’s all.

Your table might look like this:

CREATE TABLE Table1
    (`id` int, `parent_id` int, `name` varchar(13),
     `path` char(10),
     `money` int)
;

And your data might look like this.

(1, 0, 'company 1', '1', 10),
(2, 1, 'child 1', '1.1', 10),
(3, 2, 'child 2', '1.1.1', 10),
(4, 1, 'child 3', '1.2', 10,),
(4, 1, 'company 2', '2', 10),
(4, 1, 'child 2.1', '2.1', 10)

The path column helps to identify which company is a subsidiary of another company. Notice that you don’t actually need to have an allmoney column. This is dynamically generated.

And how do you find all the money that belongs to the first company?

select sum(money) from Table1 where path >= '1' and path < '2'

Notice that in the structure that we have created, child1 is the parent for child2. So how do we find the allmoney for child1?

select sum(money) from Table1 where path >= '1.1' and path < '1.2'

There is only one query and no recursion.

MPTT

Another popular approach for fetching hierarchical data is using Modified Pre Order Tree Traversal. There has been an excellent article on Sitepoint for many years which explains how this is done with lot’s of sample code.

Leave a Comment