PostgreSQL get parent categories from table

后端 未结 1 1496
不知归路
不知归路 2021-01-07 16:01

I have the table as like below.

CREATE TABLE my.categories (id bigint, parent_id bigint, name varchar(128));

INSERT INTO my.categories (id, parent_id, name)         


        
相关标签:
1条回答
  • 2021-01-07 16:21

    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).

    0 讨论(0)
提交回复
热议问题