使用 Postgres ltree 常用来存储产品类别的推荐方法是什么?
例如,我的列可以包含一个 ltree 路径,例如"1.2.3"where 1、2和3是可以显示给用户的类别标签表的外键:
categories
id | name
---+-----------
1 | Hardware
---+-----------
2 | Computers
---+-----------
3 | Video Cards
---+-----------
Run Code Online (Sandbox Code Playgroud)
现在,对于给定的产品,我想选择它的类别并将其具体化,例如"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;
Run Code Online (Sandbox Code Playgroud)
这一行:
regexp_split_to_table(p.category::text, '[.]') WITH ORDINALITY t(category, ord)
Run Code Online (Sandbox Code Playgroud)
获取该ltree列,然后将其分成多行,ltree. 该WITH ORDINALITY子句将在输出中添加一个行号,这里使用 alias 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;
Run Code Online (Sandbox Code Playgroud)
这效率较低,因为ltree必须针对其中包含的每个单独元素进行解析 ( subltree(...))。