查找树中所有非空类别

发布于 2024-09-17 19:24:38 字数 367 浏览 3 评论 0原文

我有一个类别表设置为 [id,name,parent_id] 和一个项目表 [id,name,category_id,visible]。我想做的是创建一个查询,该查询将返回所有非空类别的所有 id,非空是因为它或其子级之一至少有一个属于它的项目。在 MySQL 中执行此操作的最佳方法是什么?

编辑

SELECT DISTINCT Category_id FROM Items

这适用于包含项目的类别,但我还需要包含类别的所有项目的父类别。该查询将与其他一些过滤器一起用作子查询。

顶级类别

-> 二级类别

--> 三级类别

---> 第 1 项

---> 第 2 项

I have a categories table set up as so [id, name, parent_id] and a items table [id, name, category_id, visible]. What I'm trying to do is create a query that will return all the ids of all non-empty categories, non empty being that it or one of it's children has at least one item belonging to it. What would be the best way to do this in MySQL?

edit

SELECT DISTINCT category_id FROM Items

This works for categories containing items, but I also need the parent categories of all item containing categories. This query will be used as a subquery along with some other filters.

Top Level Category

->Second Level Category

-->Third Level Category

--->Item 1

--->Item 2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

白芷 2024-09-24 19:24:38

也许偏离主题,但我认为它仍然值得参考:有关管理的广泛文章MySQL 中的分层数据

Maybe off topic, but I think it is still worth referencing: Extensive Article on Managing Hierarchical Data in MySQL.

夜访吸血鬼 2024-09-24 19:24:38

所有非空类别(只有那些)都有 category_id 指向它们的项目,因此您可以从项目表中选择 category_id

SELECT DISTINCT category_id FROM Items

据我所知,您无法在一个查询中选择这些类别的所有祖先,但是您可能想要使用另一种树模型。

使用嵌套集模型,您的查询可能如下所示:

SELECT DISTINCT c.id FROM Categories c JOIN Items ON c.id = category_id JOIN Categories ancestors ON c.lft BETWEEN ancestors.lft AND ancestors.rgt

我不确定它是否有效,但你可以尝试一下。

All non-empty categories, and only those, have items with category_id pointing at them, therefore you could just select category_ids from items table:

SELECT DISTINCT category_id FROM Items

As far as I know, you can't select all the ancestors of these categories in one query, however you might want to use another tree model.

With the nested set model, your query could look like this:

SELECT DISTINCT c.id FROM Categories c JOIN Items ON c.id = category_id JOIN Categories ancestors ON c.lft BETWEEN ancestors.lft AND ancestors.rgt

I'm not sure if it'll work, but you can try.

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