选择一棵树并使用PostgreSQL命令孩子

时间:2013-08-23 09:15:24

标签: sql postgresql

我有下表。

CREATE TABLE categories (
    id          integer serial primary key
    parent_id   integer
    name        text    not null
    ordering    integer not null
);

我想选择所有类别,但缩进子类别的名称并将子类别放在其父类别下。在同一级别内,它们应按ordering排序。

我目前有以下查询,但返回的子类别的顺序不正确。相反,他们被命令绝对而不是相对于他们的兄弟

WITH RECURSIVE recurse_categories(id, level, name, ordering) AS (
    SELECT id, 0 AS level, name, ordering
      FROM categories
     WHERE parent_id IS NULL

    UNION ALL

    SELECT c.id, level + 1, c.name, c.ordering
      FROM categories AS c
      JOIN recurse_categories rc
        ON rc.id = c.parent_id
)

  SELECT id, repeat('→', level) || ' ' || name AS name
    FROM recurse_categories
ORDER BY ordering

如何正确排序?

我正在使用PostgreSQL 9.2.4。

1 个答案:

答案 0 :(得分:1)

累积排序到字符串:

WITH RECURSIVE recurse_categories(id, level, name, ordering) AS (
    SELECT id, 0 AS level, name, lpad(ordering::text, 10, '0') as ordering
      FROM categories
     WHERE parent_id IS NULL

    UNION ALL

    SELECT c.id, level + 1, c.name, rc.ordering || '→' || lpad(c.ordering::text, 10, '0') as ordering
      FROM categories AS c
      JOIN recurse_categories rc
        ON rc.id = c.parent_id
)

  SELECT id, repeat('→', level) || ' ' || name AS name, ordering
    FROM recurse_categories
ORDER BY ordering

sql fiddle demo