如何从类别表中以分级形式输出所有类别和子类别?

时间:2019-01-25 03:13:36

标签: sql postgresql

我有一个带有列UPDATE table2 t SET col2 = o.sum_q FROM ( SELECT sku, sum(quantity) AS sum_q FROM orders WHERE location = 'Location - 1' GROUP BY sku ) o WHERE t.sku = o.sku AND t.col2 IS DISTINCT FROM o.sumq; 的类别表。我有一个产品类别,例如..珠宝和手表>珠宝>耳环。

我的类别如下

id, name, level, parent_id

我如何编写查询,将获得以下输出结果

id, name, level, parent_id
1, Jewellery and watches, L1, null
2, Jewellery, L2, 1,
3, Ear-rings, L3, 2

1 个答案:

答案 0 :(得分:1)

使用递归查询。

with recursive top_down as (
    select id, parent_id, name, name as display_name
    from categories
    where parent_id is null
union all
    select t.id, t.parent_id, t.name, concat(display_name, ' > ', t.name)
    from categories t
    join top_down r on t.parent_id = r.id
)
select id, name, display_name
from top_down;

 id |         name          |                 display_name                  
----+-----------------------+-----------------------------------------------
  1 | Jewellery and watches | Jewellery and watches
  2 | Jewellery             | Jewellery and watches > Jewellery
  3 | Ear-rings             | Jewellery and watches > Jewellery > Ear-rings
(3 rows)

请注意,列level基本上是多余的。