postgresql - 如何将 Postgres ltree 加入标签表?

标签 postgresql ltree

使用 Postgres ltree 存储产品类别的推荐方法是什么?

例如,我的专栏可能包含一个 ltree 路径,例如 "1.2.3",其中 12 3 是可以向用户显示的类别标签表的外键:

categories

id | name
---+-----------
 1 | Hardware
---+-----------
 2 | Computers
---+-----------
 3 | Video Cards
---+-----------

现在,对于给定的产品,我想选择它的类别并将其具体化为 "Hardware > Computers > Video Cards"

最佳答案

PG 9.4+ 中:

SELECT p.id, string_agg(c.name, ' > ' ORDER BY t.ord) AS label
FROM product p
JOIN regexp_split_to_table(p.category::text, '[.]') WITH ORDINALITY t(category, ord) ON true
JOIN categories c ON c.id = t.category::int
GROUP BY p.id;

这一行:

regexp_split_to_table(p.category::text, '[.]') WITH ORDINALITY t(category, ord)

获取 ltree 列,然后将其分成几行,每行对应 ltree 中的每个元素。 WITH ORDINALITY 子句将向输出添加一个行号,这里使用别名 ord。该行号在 string_agg() 函数中使用,以保持类别标签的正确顺序。

如果您使用的是 旧版本的 PG (9.0+) 那么(您应该升级,否则)您应该这样做:

SELECT p.id, string_agg(c.name, ' > ' ORDER BY t.ord) AS label
FROM product p
JOIN generate_series(1, nlevel(p.category)) t(ord) ON true
JOIN categories c ON c.id = subltree(p.category, t.ord - 1, t.ord)::text::int
GROUP BY p.id;

这样效率较低,因为必须针对其中包含的每个单独元素解析 ltree (subltree(...))。

关于postgresql - 如何将 Postgres ltree 加入标签表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31863026/

相关文章:

postgresql - 如何撤销对用户 postgres 的复制访问权限?

json - 分层 JSON 对象的 PostgreSQL 物化路径/Ltree

java - 在 hibernate 中映射 PostgreSQL LTREE 列时出错

PostgreSQL:快速检查 LTREE [] <@ LTREE[] 的所有元素是否

postgresql - wso2 GREG 4.5.0 和 postgresql 作为外部数据库的问题

postgresql - Postgres : getting the maximum and minimum values, 和它们出现的时间戳

Django:JSONField + 全文搜索 + 索引 -> 序列扫描。如何配置索引工作?

java - 使用 spring data jpa 的 ltree postgres 类型 - 在 postgres 中定义函数和转换后出现语法错误

postgresql - 使用ltree Postgres插件仅返回子结构

java - 如何在 HQL 中传递特殊字符?