PostgreSQL get parent categories from table

强颜欢笑 提交于 2019-12-01 01:50:17

If I get you, this is what you need.

First, with the folowing query you can get all the parent ids:

WITH RECURSIVE t(id, parentlist) AS (
  SELECT id, ARRAY[]::bigint[] FROM my.categories WHERE parent_id IS NULL
  UNION
  SELECT my.categories.id, my.categories.parent_id || t.parentlist
    FROM my.categories 
    JOIN t ON categories.parent_id = t.id
) SELECT * FROM t
-- outputs:
-- id  | parentlist
-- ----+------------
-- 1   | {}
-- 2   | {1}
-- 3   | {1}
-- 4   | {2,1}
-- 5   | {2,1}
-- 6   | {3,1}

If you want to get a record of the parents of one id you just need to change the query like:

WITH RECURSIVE t(id, parentlist) AS (
  SELECT id, ARRAY[]::bigint[] FROM my.categories WHERE parent_id IS NULL
  UNION
  SELECT my.categories.id, my.categories.parent_id || t.parentlist
    FROM my.categories 
    JOIN t ON categories.parent_id = t.id
) SELECT unnest(parentlist) as parents_ids FROM t WHERE id=6;
-- outputs:
-- parents_ids
-- -----------
-- 3
-- 1

Note that the last query does not output the "current" id (6).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!