MySQL 查询合并连接表和嵌套集

发布于 2024-09-12 17:11:27 字数 1092 浏览 2 评论 0原文

我有三个表:categoriestagstaggings。类别表以嵌套集的方式组合在一起,包含相关列 idlftrgtparent_id< /代码>。标签有idname。标签有 tag_idtaggable_id,它引用 categories.id

如果可能的话,我想要一个在字段中返回的查询,例如 tag_list,一个包含类别及其所有祖先标签的字符串。 给出以下架构:

类别

id | parent_id | lft | rgt
 1 |      NULL |   1 |   6
 2 |         1 |   2 |   5
 3 |         2 |   3 |   4

标签

id | name
 1 | cool
 2 |  rad
 3 | soup

因此,

id | tag_id | taggable_id
 1 |      1 |           1
 2 |      2 |           2
 3 |      3 |           3

我想要查询 SELECT ??? FROMcategories 返回:

id |      tag_list
 1 |          cool
 2 |      rad cool
 3 | rad cool soup

背景信息:我正在运行 Rails,并且使用 Thinking Sphinx 进行搜索,使用 Awesome_nested_set 进行嵌套。我有一个名为 categories 的表,其中有许多处于 has_many_through 关系中的 tag

I have three tables, categories, tags, and taggings. The categories table is put together in the fashion of a nested set, with relevant columns id, lft, rgt, and parent_id. Tags has id and name. Taggings has tag_id and taggable_id, which refers to categories.id.

If possible, I'd like for one query which returns in a field, say tag_list, a string containing a category's and all of its ancestors' tags. So given the following schema:

Categories

id | parent_id | lft | rgt
 1 |      NULL |   1 |   6
 2 |         1 |   2 |   5
 3 |         2 |   3 |   4

Tags

id | name
 1 | cool
 2 |  rad
 3 | soup

Taggings

id | tag_id | taggable_id
 1 |      1 |           1
 2 |      2 |           2
 3 |      3 |           3

I'd like for the query SELECT ??? FROM categories to return:

id |      tag_list
 1 |          cool
 2 |      rad cool
 3 | rad cool soup

Background info: I'm running Rails, and I'm using Thinking Sphinx for search and awesome_nested_set for nesting. I have a table called categories, which has many tags in a has_many_through relationship.

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

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

发布评论

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

评论(1

盗梦空间 2024-09-19 17:11:27
SELECT node_id, group_concat(name SEPARATOR ' ')
FROM taggings INNER JOIN tags ON taggings.tag_id=tags.id
INNER JOIN (SELECT node.id AS node_id, parent.id AS parent_id
FROM categories AS node,
categories AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt) subcategories
ON subcategories.parent_id=taggings.taggable_id
GROUP BY (node_id);

好吧,我在这样做时学到了一三件事:)

编辑:我没有针对 mysql 进行检查,只针对 SQLite 进行检查,因此语法可能不是 100%。

SELECT node_id, group_concat(name SEPARATOR ' ')
FROM taggings INNER JOIN tags ON taggings.tag_id=tags.id
INNER JOIN (SELECT node.id AS node_id, parent.id AS parent_id
FROM categories AS node,
categories AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt) subcategories
ON subcategories.parent_id=taggings.taggable_id
GROUP BY (node_id);

Well, I for one learned a thing or three doing that :)

EDIT: I did not check it against mysql, only SQLite, so the syntax might not be 100%.

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