PostgreSQL从表中获取父类别

时间:2018-04-11 09:56:14

标签: postgresql recursive-query

我的表格如下所示。

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

INSERT INTO my.categories (id, parent_id, name) VALUES (1, null, 'LEVEL 1');
INSERT INTO my.categories (id, parent_id, name) VALUES (2, 1, 'LEVEL 2.1');
INSERT INTO my.categories (id, parent_id, name) VALUES (3, 1, 'LEVEL 2.2');
INSERT INTO my.categories (id, parent_id, name) VALUES (4, 2, 'LEVEL 3.1.1');
INSERT INTO my.categories (id, parent_id, name) VALUES (5, 2, 'LEVEL 3.1.2');
INSERT INTO my.categories (id, parent_id, name) VALUES (6, 3, 'LEVEL 3.2.1');

+----+-----------+---------------+
| id | parent_id | name          |
+----+-----------+---------------+
|  1 |      null |     'LEVEL 1' |
|  2 |         1 |   'LEVEL 2.1' |
|  3 |         1 |   'LEVEL 2.2' |
|  4 |         2 | 'LEVEL 3.1.1' |
|  5 |         2 | 'LEVEL 3.1.2' |
|  6 |         3 | 'LEVEL 3.2.1' |
+----+-----------+---------------+

我需要为父类别获取所有内容。

WITH RECURSIVE tree(theId) AS (
  SELECT id
  FROM my.categories
  WHERE id = theId -- wrong here, because its not a procedure
  UNION ALL
  SELECT table1.id
  FROM my.categories AS table1
    JOIN tree AS parent ON theId = table1.parent_id
)
SELECT DISTINCT theId FROM tree WHERE theId = 6;

数据的示例结果,但实际上我只需要id。

+----+-----------+---------------+
| id | parent_id | name          |
+----+-----------+---------------+
|  1 |      null |     'LEVEL 1' |
|  3 |         1 |   'LEVEL 2.2' |
|  6 |         3 | 'LEVEL 3.2.1' |
+----+-----------+---------------+

或者像这样:

+----+-----------+---------------+
| id | parent_id | name          |
+----+-----------+---------------+
|  3 |         1 |   'LEVEL 2.2' |
|  6 |         3 | 'LEVEL 3.2.1' |
+----+-----------+---------------+

问题是我不允许使用程序。此查询应该用作许多其他查询的子查询。请不要看name栏,这是无关紧要的。

1 个答案:

答案 0 :(得分:1)

如果我找到你,这就是你需要的。

首先,通过以下查询,您可以获得所有父ID:

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}

如果您想获得一个id的父母的记录,您只需要更改查询:

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

请注意,最后一个查询不输出“当前”ID(6)。