SQL递归查询,关于理解connect by子句中“先前”表达式的问题

问题描述 投票:0回答:1

我创建了一个如下表,以了解递归查询:

enter image description here

enter image description here

为此,我进行了插入操作,导致查询循环,现在我的表如下所示(已添加雅典与维也纳的连接:]

enter image description here

现在进行一个非循环的递归查询,我使用connect by函数并在下面编写了代码:

select distinct abflug,ankunft,level from flugverbindungen
start with ABFLUG = 'Wien'
connect by nocycle prior ankunft =  abflug
order by level;

此结果出来了:

enter image description here

我可以看到查询一直运行到维也纳,然后在Pressburg结束。但是,当我像这样将先前的表达式从ankunft更改为abflug时:

select distinct abflug,ankunft,level from flugverbindungen
    start with ABFLUG = 'Wien'
    connect by nocycle  ankunft = prior abflug
    order by level;

我得到以下结果:

enter image description here

现在雅典到维也纳的等级为2,这很奇怪,因为根节点应该是维也纳而不是雅典。我也不明白,莱巴赫到贝尔格莱德是怎么变成4级的。

总之,我实际上不理解先验表达式在查询中发生了什么变化,以及它对查询有什么好处。当您使用此示例解释先前的表达式时,我将非常感激。当我交换前面的表达式的一侧时,实际上发生了什么变化?

sql hierarchy recursive-query connect-by
1个回答
0
投票
您可以使用递归CTE遍历图形。例如:

with c (abflug, ankunft, lvl) as ( select abflug, ankunft, 1 from t where abflug = 'Wien' union all select t.abflug, t.ankunft, c.lvl + 1 from c join t on t.abflug = c.ankunft and c.lvl <= 4 ) select * from c;

结果:

ABFLUG ANKUNFT LVL ------- --------- --- Wien Pressburg 1 Wien Laibach 1 Laibach Paris 2 Laibach Belgrad 2 Belgrad Athen 3 Athen Wien 4 Wien Pressburg 5 Wien Laibach 5

请参见db<>fiddle处的运行示例。
© www.soinside.com 2019 - 2024. All rights reserved.