mario
mario

Reputation: 177

MySQL Query Parent Child

I am working with mysql and php and have a Parent Child table created in mysql. Every parent has 3 Childs. Every Child becomes also a Parent and has also 3 Childs and so on.

Now I need to write a function that gives me the last parent in the tree (depending on the selected parent ID) that does not have 3 Childs. So the next Child subscription can be dedicated to that parent.

Can this be done with mysql query or function?

Thanks, M


I use the following query:

SELECT t1.uid, t2.pid FROM cms_users AS t1 LEFT JOIN cms_users AS t2 ON t1.uid = t2.pid 

Which gives mr the following output:

t1.uid t2.pid
1      1 
1      1 
1      1 
2      2 
2      2 
2      2 
3      3 
4      NULL 
5      NULL

What I actualy need is a result like:

p1.uid p2.pid 
1      3 
2      3 
3      1 
4      0 
5      0 

This result also starts from the root Parent 1 I need to get the results starting from a selected uid somewhere in the three. Every parent has his own tree starting from his uid. Probably I need to write a stored procedure or something but this is all new to me and I don't know how to do this.

This is an example of how the tree looks like. http://www.musafreaks.com/images/tree.jpg User ID 1 has his own tree, even user 2, 3 and 4 have there own tree and so on.

Upvotes: 1

Views: 2008

Answers (1)

svens
svens

Reputation: 11628

This problem is not trivial to solve within MySQL. Multiple strategies to manage hierarchical data are described in the manual. The rest of my answer is based on this article.

Your setup is sort of a "Adjacency List Model", so you could adapt the LEFT JOIN solution for your dataset.

SELECT t1.name FROM
category AS t1 LEFT JOIN category as t2
ON t1.category_id = t2.parent
WHERE t2.category_id IS NULL;

This assumes that the parent field of the root node is null. Your possible new parent will be selected as t1. Note that this query will return all nodes which have no children, if you want to "fill" up each node with three children you'll have to extend the query a bit.

Upvotes: 2

Related Questions