假设我有如下的类别层次结构:
id | name | parent_id
---+------------+-----------
1 | Computers |
---+------------+-----------
2 | Laptops | 1
---+------------+-----------
3 | Desktops | 1
---+------------+-----------
4 | Big | 2
---+------------+-----------
5 | Small | 2
---+------------+-----------
4 | Big | 3
---+------------+-----------
5 | Small | 3
现在,假设有人给我输入['Computers', 'Laptops', 'Small']
。Postgres 中查询层次结构并到达正确的最终类别(例如 id 5)的最佳方法是什么?
我知道您可以使用递归 CTE 遍历树,但是将输入数组参数化到查询中的最佳方法是什么?
以下或多或少有效,但感觉真的低于标准,因为您必须拆分参数数组:
WITH RECURSIVE path(n, id, name, parent_id) AS (
SELECT
1, c.id, c.name, c.parent_id
FROM
categories c
WHERE c.name = 'Computers' AND parent_id IS NULL
UNION ALL
SELECT n+1, c.id, c.name, c.parent_id
FROM categories c,
(SELECT * FROM unnest(ARRAY['Laptops', 'Small']) WITH ORDINALITY np(name, m)) np,
path p
WHERE c.parent_id = p.id AND np.m = n AND np.name = c.name
)
SELECT * FROM path;