递归选择MySQL中最顶层的递归
我有一个表,它纯粹保存一个应用程序的组之间的关系,该应用程序可以有无限数量的子组。
CREATE TABLE `shop_groups_group_rel` (
`id_group` int(11) NOT NULL,
`id_parent` int(11) NOT NULL,
`type` enum('shop','group') NOT NULL
);
“商店”类型基本上意味着它的最顶层。
现在我需要能够获得我可能解析的任何组的最顶层组。我已经研究了 MySQL 的 LOOP 语法,但我不知道如何将其与数据库上的实际查询混合。
谁能给我一个提示,告诉我如何能够递归地选择父组,直到我位于最顶层的组?
我知道这样做可能有风险,因为可能有无限数量的子组,但实际上这永远不会超过 2 或 3 个子组,我可以轻松地对此施加硬性限制。
谢谢
I have a table which holds purely the relations between groups for an app that can have an infinite amount of sub groups.
CREATE TABLE `shop_groups_group_rel` (
`id_group` int(11) NOT NULL,
`id_parent` int(11) NOT NULL,
`type` enum('shop','group') NOT NULL
);
Type "shop" basically means its top most.
Now I need to be able to get the top most group for ANY group I might be parsing in. I've looked into MySQL's LOOP syntax but I can't figure out how to mix this with actual queries on the database.
Can anyone give me a hint as to how I might be able to recursively select the parent group until I am at the top most group?
I know that doing this can be risky seeing as there can be infinite amount of subgroups but in practice this will never be more than 2 or 3 subgroups and I can easily impose a hard limit on this.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您接受硬限制,则可以使用联接。
它显然不是递归的,因此您不能无限期地继续下去,但您可以在数据集中添加您合理期望的任意数量的联接。它不是很快,但它至少会短路,因为一旦到达顶部父级,它基本上会跳过其余的连接。
If you're ok with a hard limit you could just use joins.
It's obviously not recursive so you can't go on indefinitely but you can add as many joins as you would reasonably expect in your data set. It's not terribly fast but it will at least short circuit in that once you reach the top parent it will basically skip the rest of the joins.