用于获取存储在单个表中的n级父子关系的Postgresql查询

前端之家收集整理的这篇文章主要介绍了用于获取存储在单个表中的n级父子关系的Postgresql查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一张表示亲子关系的表.关系可以深入n级.

我已经使用以下查询创建了一个示例表:

CREATE SEQUENCE relations_rel_id_seq
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;
CREATE TABLE relations(
    rel_id bigint DEFAULT nextval('relations_rel_id_seq'::regclass) NOT NULL PRIMARY KEY,rel_name text,rel_display text,rel_parent bigint
);

SQLFiddle

我需要查询表并分层显示父子关系.我仍然不了解如何使用SQL查询查询n级深度.

对于sqlfiddle,例如,输出的预期层次结构:

rel1
    rel11
        rel111
        rel112
            rel1121
rel2
    rel21
        rel211
        rel212

N.B:n级中的值n是未知的.

数据库设计:

Is there any better way such a relation can be expressed in the
database for easy querying.?

使用Postgres可以使用递归公用表表达式:
with recursive rel_tree as (
   select rel_id,rel_name,rel_parent,1 as level,array[rel_id] as path_info
   from relations 
   where rel_parent is null
   union all
   select c.rel_id,rpad(' ',p.level * 2) || c.rel_name,c.rel_parent,p.level + 1,p.path_info||c.rel_id
   from relations c
     join rel_tree p on c.rel_parent = p.rel_id
)
select rel_id,rel_name
from rel_tree
order by path_info;

基于您的示例sqlFiddle:http://sqlfiddle.com/#!11/59319/19

(我用空格替换了下划线,因为sqlFiddle不会正确显示空格)

原文链接:https://www.f2er.com/postgresql/191790.html

猜你在找的Postgre SQL相关文章