SQL 按源、目标序列等两列排序

SQL order by two columns like source, target sequence

我的 table 是这样的:

ID  SOURCE  TARGET
1      9      8
2      0      7
3      5      4
4      4      9
5      7      5

那么,我怎样才能将其制作成:

ID  SOURCE  TARGET
2      0      7
5      7      5
3      5      4
4      4      9
1      9      8

从按目标排序的“0”开始,接下来的源列...

drop table if exists test;
create table  test(id integer, source integer, target integer);

DROP INDEX IF EXISTS idx_ts;

CREATE INDEX idx_ts
  ON test
  USING btree
  (source);

DROP INDEX IF EXISTS public.idx_tt;

CREATE INDEX idx_tt
  ON test
  USING btree
  (target);


insert into  test values(1, 9, 8);
insert into  test values(2, 0, 7);
insert into  test values(3, 5, 4);
insert into  test values(4, 4, 9);
insert into  test values(5, 7, 5);

这是我的样本 table。

这可以使用构建树的递归查询来完成。为了获得正确的层次结构顺序,您需要计算每行的 "level" 。

with recursive targets as (
  select id, source, target, 1 as level
  from omar
  where source = 0
  union all
  select c.id, c.source, c.target, p.level + 1
  from omar c 
    join targets p on c.source = p.target
)
select id, source, target
from targets
order by level;

由于您的层级是 "flat",因此只需计算基本上与起点的距离的级别就足够了。

有关递归查询的更多详细信息check out the tutorial in the Postgres manual