递归选择MySQL中最顶层的递归

发布于 2024-10-06 02:53:44 字数 450 浏览 4 评论 0原文

我有一个表,它纯粹保存一个应用程序的组之间的关系,该应用程序可以有无限数量的子组。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷︶言冷语的世界 2024-10-13 02:53:44

如果您接受硬限制,则可以使用联接。

SELECT id_group,
COALESCE(p4.id_group, p3.id_group, p2.id_group, p1.id_group, g.id_group) 
  as top_id_group
FROM shop_groups_group_rel g
LEFT JOIN shop_groups_group_rel p1 ON p1.id_group = g.id_parent
LEFT JOIN shop_groups_group_rel p2 ON p2.id_group = p1.id_parent
LEFT JOIN shop_groups_group_rel p3 ON p3.id_group = p2.id_parent
LEFT JOIN shop_groups_group_rel p4 ON p4.id_group = p3.id_parent

它显然不是递归的,因此您不能无限期地继续下去,但您可以在数据集中添加您合理期望的任意数量的联接。它不是很快,但它至少会短路,因为一旦到达顶部父级,它基本上会跳过其余的连接。

If you're ok with a hard limit you could just use joins.

SELECT id_group,
COALESCE(p4.id_group, p3.id_group, p2.id_group, p1.id_group, g.id_group) 
  as top_id_group
FROM shop_groups_group_rel g
LEFT JOIN shop_groups_group_rel p1 ON p1.id_group = g.id_parent
LEFT JOIN shop_groups_group_rel p2 ON p2.id_group = p1.id_parent
LEFT JOIN shop_groups_group_rel p3 ON p3.id_group = p2.id_parent
LEFT JOIN shop_groups_group_rel p4 ON p4.id_group = p3.id_parent

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文