检索按PostgreSQL的Ltree模块下的列排序的完整层次结构 [英] Retrieving full hierarchy sorted by a column under PostgreSQL's Ltree module

查看:114
本文介绍了检索按PostgreSQL的Ltree模块下的列排序的完整层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PostgreSQL的 Ltree 模块来存储分层数据.我正在寻找按特定列排序的完整层次结构.

I'm using PostgreSQL's Ltree module for storing hierarchical data. I'm looking to retrieve the full hierarchy sorted by a particular column.

请考虑下表:

  votes | path  | ...
 -------+-------+-----
      1 | 1     | ...
      2 | 1.1   | ...
      4 | 1.2   | ...
      1 | 1.2.1 | ...
      3 | 2     | ...
      1 | 2.1   | ...
      2 | 2.1.1 | ...
      4 | 2.1.2 | ...
    ... | ...   | ...

在当前的实现中,我将使用 SELECT * FROM注释ORDER BY路径查询数据库,这将返回整个树:

In my current implementation, I'd query the database with SELECT * FROM comments ORDER BY path, which would return the whole tree:

Node 1
-- Node 1.1
-- Node 1.2
---- Node 1.2.1
Node 2
-- Node 2.1
---- Node 2.1.1
---- Node 2.1.2

不过,我想按投票排序(而不是按 path 进行排序的 id ).每个深度级别都需要独立排序,并保持正确的树结构完整.会返回以下内容的东西:

However, I want to sort by votes (not by id, which is what sorting by path amounts to). Each depth level needs to be independently sorted, with the correct tree structure kept intact. Something that would return the following:

Node 2
-- Node 2.1
---- Node 2.1.2
---- Node 2.1.1
Node 1
-- Node 1.2
---- Node 1.2.1
-- Node 1.1

Postgres的 WEAR RECURSIVE 可能合适,但我不确定.有什么想法吗?

Postgres' WITH RECURSIVE might be appropriate, but I'm not sure. Any ideas?

推荐答案

使用 被遗忘的 .

WITH RECURSIVE t AS (
    SELECT t.votes
         , t.path
         , 1::int AS lvl
         , to_char(t2.votes, 'FM0000000')  AS sort
    FROM   tbl t
    JOIN   tbl t2 ON t2.path = subltree(t.path, 0, 1)

    UNION ALL
    SELECT t.votes
         , t.path
         , t.lvl + 1
         , t.sort || to_char(t2.votes, 'FM0000000')
    FROM   t
    JOIN   tbl t2 ON t2.path = subltree(t.path, 0, t.lvl + 1)
    WHERE  nlevel(t.path) > t.lvl
    )
SELECT votes, path, max(sort) AS sort
FROM   t
GROUP  BY 1, 2
ORDER  BY max(sort), path;

要点

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆