SQL-POSTGRESQL : 按照一定的标准对 table 进行排序

SQL-POSTGRESQL : sorting table according to a certain criteria

所以我有这个table

person_id    child      mom 

1            john       marry
2            mark       sophia
3            emma       null
4            alfonso    marry
5            sophia     null
6            marry      isabella
7            michael    emma
8            isabella   null

我想以每个妈妈都有她的 children 的方式对这个 table 进行排序。 例如

person_id    child       mom 

1            isabella    null
2            marry       isabella
3            john        marry
4            alfonso     marry
5            sophia      null
6            mark        sophia
7            emma        null
8            michael     emma

注意:妈妈可以既是妈妈又是 child 例如:marry 有 2 children(john 和 alfonso),但她是也是伊莎贝拉的女儿

有什么方法可以在 sql 中实现这一点?

如果我没听错,你需要一个递归查询:

with recursive cte as (
    select t.*, array[person_id] path from mytable t where mom is null
    union all
    select t.*, c.path || t.person_id
    from cte c
    inner join mytable t on t.mom = c.child
)
select * from cte order by path

我们的想法是构建每一行的路径,然后您可以使用它来对结果集进行排序。

Demo on DB Fiddle:

person_id | child    | mom      | path   
--------: | :------- | :------- | :------
        3 | emma     | null     | {3}    
        7 | michael  | emma     | {3,7}  
        5 | sophia   | null     | {5}    
        2 | mark     | sophia   | {5,2}  
        8 | isabella | null     | {8}    
        6 | marry    | isabella | {8,6}  
        1 | john     | marry    | {8,6,1}
        4 | alfonso  | marry    | {8,6,4}