如何在单个查询中将孩子和父母分组? [英] How can I group children and parents in a single query?

查看:99
本文介绍了如何在单个查询中将孩子和父母分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,代表一个简单的父级->子级层次结构,例如:

I have a table that represents a simple parent->child hierarchy, something like:

             Table "public.transactions"
   Column  | Type          |  Modifiers
-----------+---------------+-----------------------------------------------------------
 id        | integer       | not null default nextval('transactions_id_seq'::regclass)
 parent_id | integer       | not null default 0
 amount    | numeric(15,4) | not null default 0.0000

我想显示带有子事务的表(那些具有parent_id> 0)分组在各自的父母之下。例如,

I'd like to display the table with child transactions (those with a parent_id > 0) grouped below their respective parents. e.g.,

parent
   child
   child
parent
   child
parent
parent

(注意:嵌套空间仅在此处用来表示

我可以在单个查询中执行此操作吗?如果有问题,我正在运行Postgresql 9.3。

Can I do this in a single query? I'm running Postgresql 9.3 in case it matters.

推荐答案

对于单层嵌套,这似乎几乎是微不足道的:

For a single level of nesting, this may seem almost trivial:

SELECT *
FROM   transactions
ORDER  BY COALESCE(parent_id, id), id

这篇关于如何在单个查询中将孩子和父母分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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