Database 如何在层次结构中返回路径的起点和终点
我有一张这样的桌子Database 如何在层次结构中返回路径的起点和终点,database,postgresql,recursive-query,Database,Postgresql,Recursive Query,我有一张这样的桌子 --------------------------- | id1 | id2 | col1 | col2 | +-----+-----+------+------+ | 1 | 1 | a | b | |-----+-----+------+------| | 1 | 2 | b | c | |-----+-----+------+------| | 5 | 1 | d | f | ----------------
---------------------------
| id1 | id2 | col1 | col2 |
+-----+-----+------+------+
| 1 | 1 | a | b |
|-----+-----+------+------|
| 1 | 2 | b | c |
|-----+-----+------+------|
| 5 | 1 | d | f |
---------------------------
其思想是该表存储路径:a->b->c和d->f。我想要的是一个返回a->c和d->f的查询。我想你的意思是
select a, b, c from whateveryourtablenameis;
除了a、b和c之外,还包括您想要的任何列
这将只返回列a、b和c。我不知道如何向SQL查询除*之外的一系列列。您需要一个递归查询:
with recursive find_path (col1, col2, depth) as (
select col1, col2, 1
from my_table t
where not exists (
select 1
from my_table
where col2 = t.col1)
union all
select p.col1, t.col2, depth+ 1
from my_table t
join find_path p on p.col2 = t.col1
)
select distinct on (col1) format('%s -> %s', col1, col2) as path
from find_path
order by col1, depth desc;
path
--------
a -> c
d -> f
(2 rows)
这个问题不太清楚。如果您的目标是按id1按id2的顺序获取分区中的路径,则可以使用窗口函数:
select distinct on (id1)
id1, first_value(col1) over w, last_value(col2) over w
from my_table
window
w as (partition by id1 order by id2)
order by id1, id2 desc;
id1 | first_value | last_value
-----+-------------+------------
1 | a | c
5 | d | f
(2 rows)