MySQL 查询父子
我正在使用 mysql 和 php,并在 mysql 中创建了一个父子表。 每个父母都有 3 个孩子。每个孩子也成为父母,并且还有 3 个孩子,依此类推。
现在我需要编写一个函数,为我提供树中最后一个没有 3 个子级的父级(取决于所选父级 ID)。因此,下一个子订阅可以专用于该父订阅。
可以用mysql查询或函数来完成吗?
谢谢, M
我使用以下查询:
SELECT t1.uid, t2.pid FROM cms_users AS t1 LEFT JOIN cms_users AS t2 ON t1.uid = t2.pid
这给出了 mr 以下输出:
t1.uid t2.pid
1 1
1 1
1 1
2 2
2 2
2 2
3 3
4 NULL
5 NULL
我实际需要的是这样的结果:
p1.uid p2.pid
1 3
2 3
3 1
4 0
5 0
这个结果也从根 Parent 1 开始 我需要从三个中的某个选定的 uid 开始获取结果。 每个父母都有自己的树,从他的 uid 开始。 也许我需要编写一个存储过程或其他东西,但这对我来说是全新的,我不知道如何做到这一点。
这是树的外观示例。 http://www.musafreaks.com/images/tree.jpg 用户 ID 1 有自己的树,甚至用户 2、3 和 4 也有自己的树,依此类推。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个问题在 MySQL 中解决起来并不简单。 手册中描述了管理分层数据的多种策略。我的其余答案基于这篇文章。
您的设置有点像“邻接列表模型”,因此您可以为您的数据集调整
LEFT JOIN
解决方案。这假设根节点的
parent
字段为null
。您可能的新父级将被选为t1
。请注意,此查询将返回没有子节点的所有节点,如果您想用三个子节点“填充”每个节点,则必须稍微扩展查询。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.This assumes that the
parent
field of the root node isnull
. Your possible new parent will be selected ast1
. 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.