Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear Friends,

I have to develop the MLM project, I want to calculate
1. Number of children from each node.
2. find the level of node.

1
/ \
2 3
/ \ / \
4 5 6 7

For Eg. Tot. no. of child for '1' is 6
Tot. no. of child for '2' is 2
Tot. no. of child for '4' is 0
...........

What I have tried:

I have db table like this:

id parent_id Leg
--------------------
1 0
2 1 L
3 1 R
4 2 L
5 2 R
6 3 L
7 3 R

I tried this function it makes error:
CREATE FUNCTION get_counts(value INT) RETURNS INT
NOT DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE _id INT;
DECLARE _parent INT;
DECLARE _next INT;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET @id = NULL;

SET _parent = @id;
SET _id = -1;

IF @id IS NULL THEN
RETURN NULL;
END IF;

LOOP
SELECT MIN(id)
INTO @id
FROM my_registration
WHERE sponser_id = _parent
AND id > _id;
IF @id IS NOT NULL OR _parent = @start_with THEN
SET @level = @level + 1;
RETURN @id;
END IF;
SET @level := @level - 1;
SELECT id, sponser_id
INTO _id, _parent
FROM my_registration
WHERE id = _parent;
END LOOP;
END

ERROR is: MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5
Posted
Updated 24-Aug-16 1:13am
v4
Comments
Patrice T 24-Aug-16 6:01am    
Each node id is a letter or a number ?
the tree have 7 nodes and the table 5 nodes.
Can you make the tree and table match ?
Vivek.anand34 24-Aug-16 6:06am    
number
Patrice T 24-Aug-16 6:09am    
Make sure that tree and table are matching.
It makes things simpler to everyone.
Use Improve question to update your question.
Vivek.anand34 24-Aug-16 6:07am    
that letter is for eg. i said

I would re-build the tree in code, using the data retrieved from the table, and then traverse it in order to compute the required values.
See, for instance: PHP Master | Data Structures for PHP Devs: Trees[^].
 
Share this answer
 
Take a sheet of paper, note the table, add 2 columns, 1 for level and 1 for childs.
Don't use your god power that gives you instant answer and try to solve the problem by hand.
Note that your only information is the parent node for every node.
Level: How do you get the level of a node in the table? What do you need to know to get the level of a random node?
Childs: How do you get the number of childs of a node in the table? What do you need to know to get the number of childs of a random node?

You should come out with a procedure to get the answers.

Nota; the table contain everything you need, no need to build the tree.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900