Postgres:按名称查询层次结构的最佳方式

时间:2015-09-22 00:30:13

标签: postgresql tree recursive-cte

假设我有一个类别层次结构如下:

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;

1 个答案:

答案 0 :(得分:1)

CTE应如下所示:

WITH RECURSIVE search AS (
  SELECT ARRAY['Computers', 'Laptops', 'Small'] AS terms
), path (n, id, name, parent_id) AS (
  SELECT 1, id, name, parent_id
  FROM categories, search
  WHERE name = terms[1]
  UNION
  SELECT p.n+1, c.id, c.name, c.parent_id
  FROM categories c, path p, search s
  WHERE c.parent_id = p.id
    AND c.name = (s.terms)[p.n+1]
)
SELECT * FROM path;

巧妙的是,您只需指定一次数组,然后CTE的其他项就会遍历数组,无论路径有多长。没有必要的替代品。请注意,这也适用于部分树:['桌面'大']将很好地产生正确的路径(显然,不包括'计算机')。 / p>

SQLFiddle here