[英]MySQL Query Parent Child
I am working with mysql and php and have a Parent Child table created in mysql.我正在使用 mysql 和 php,并在 mysql 中创建了一个父子表。 Every parent has 3 Childs.
每个父母有3个孩子。 Every Child becomes also a Parent and has also 3 Childs and so on.
每个孩子也成为父母,也有 3 个孩子,依此类推。
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.现在我需要编写一个函数,该函数为我提供树中的最后一个父节点(取决于所选的父节点 ID),它没有 3 个子节点。 So the next Child subscription can be dedicated to that parent.
因此,下一个子订阅可以专用于该父级。
Can this be done with mysql query or function?这可以用 mysql 查询或函数来完成吗?
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.这个结果也从根父 1 开始,我需要从三个中某个选定的 uid 开始获取结果。 Every parent has his own tree starting from his uid.
每个父母都有自己的树,从他的 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.
http://www.musafreaks.com/images/tree.jpg用户 ID 1 有自己的树,甚至用户 2、3 和 4 也有自己的树等等。
This problem is not trivial to solve within MySQL.这个问题在 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.您的设置类似于“邻接列表模型”,因此您可以为您的数据集调整
LEFT JOIN
解决方案。
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
.这假设根节点的
parent
字段为null
。 Your possible new parent will be selected as t1
.您可能的新父母将被选为
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.请注意,此查询将返回所有没有子节点的节点,如果您想用三个子节点“填充”每个节点,则必须稍微扩展查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.