postgresql - 使用层次结构对列进行排序,并使用附加列进行排序

标签 postgresql sorting hierarchical-data

我有以下结构:

id,
name,
parent_id,
order_by

和条目:

 id |    name   | parent_id | order_by 
----+-----------+-----------+----------
  8 | Cat 1     |           |        1
  7 | Cat 2     |           |        2
  5 | Cat 3     |           |        3
 15 | Cat 1.1   |         8 |        1
 17 | Cat 1.2   |        15 |        2
 16 | Cat 2.1   |         8 |        1
 20 | Cat 1.2.1 |        17 |        1

我想输出:

 id |    name   | parent_id | order_by 
----+-----------+-----------+----------
  8 | Cat 1     |           |        1
 15 | Cat 1.1   |         8 |        1
 17 | Cat 1.2   |         8 |        2
 20 | Cat 1.2.1 |        17 |        1
  7 | Cat 2     |           |        2
 16 | Cat 2.1   |         7 |        1
  5 | Cat 3     |           |        3

因此,使用 order_by 列对主要条目(不带parent_id)进行排序,并使用 order_by 列对某一级别的子项进行排序。

最佳答案

注意:我假设对于 id = 16,parent_id 应该是 7,而不是 8


您需要一个递归查询来遍历整个树。您需要一种方法来“记住”主要排序顺序,然后按两个不同的标准排序:一个用于“总体”排序顺序,一个用于每个子级别:

with recursive tree as (
   select id, name, parent_id, order_by as main_order, null::int as child_order
   from category
   where parent_id is null
   union all
   select c.id, c.name, c.parent_id, p.main_order, c.order_by as child_order
   from category c
     join tree p on p.id = c.parent_id
)
select *
from tree 
order by main_order, child_order nulls first;

通过将 order_by 从根级别传递给所有子级,我们可以将属于同一根的所有行保留在一起。然后,根据假的 child_order 对一个根的行进行排序 - 根行的该列将具有 null,并且 nulls first 将它们放在每组的开头。


在线示例:http://rextester.com/ZVLII98217

关于postgresql - 使用层次结构对列进行排序,并使用附加列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47063492/

相关文章:

javascript - 在 JSON 对象中排序数组给出 TypeError : Cannot read property 'sort' of undefined

对不需要不同的 n 个正整数键的列表 L 进行排序的算法。应该具有 O(n+N) 的复杂性,其中 N = maxL(i) - minL(i)

javascript - 从具有根和子条件的数组构建分层树的最佳方法

mysql - 如何在 mySQL 中建模可选的自相关性?

sql - DBI 的 column_info 与 pgAdmin 在引用标识符上的对比

postgresql - 大型客户端连接上的 Pgbouncer

postgresql - 是否可以防止删除而不是插入外键?

带有本地化的 Postgresql 数据库创建问题

c++ - 在循环中对 vector 进行排序

c# - 在 asp.net MVC 中使用 jQuery 和 AJAX 自动填充选择框