【问题标题】:How to calculate number of hops between sourcee and destination?如何计算源和目标之间的跳数?
【发布时间】:2020-06-30 18:27:48
【问题描述】:

我在表源和目标中有两列,如下所示。

source delivery
  s1      d1
  d1      d2
  d2      f1
  s2      d3
  d3      d4
  d4      d5
  d5      f2

  source - s1 destination f1
  source - s2 destination f2

如何获取源和目的地之间的停靠点数? 例如:源 s1 -> 目标 f1 在它们之间有 3 个停靠点,并且 源 s2 -> 目标 f2 在它们之间有 4 个停靠点

我熟悉 SQL 查询,但从未编写过或遇到过这样的问题。 谁能让我知道如何为上述问题编写一个 sql 查询? 即使有另一个问题与相同的问题,该链接/问题可以帮助我理解如何编写它。

【问题讨论】:

  • 在 MySQL 中你需要一个递归 CTE,它只在 MySQL 8+ 中可用。
  • 其他选项包括尽可能频繁地将表连接到自身、切换到嵌套集模型或处理应用程序级代码中的递归。

标签: mysql sql recursive-query hierarchical-query


【解决方案1】:

如果您运行的是 MySQL 8.0,则可以使用递归查询来执行此操作:

with recursive cte as (
    select source, delivery, 1 hops 
    from mytable t
    where not exists (select 1 from mytable t1 where t1.delivery = t.source)
    union all 
    select c.source, t.delivery, c.hops + 1
    from cte c
    inner join mytable t on t.source = c.delivery
)
select source, delivery, hops
from cte c
where hops = (select max(c1.hops) from cte c1 where c1.source = c.source)

递归查询的锚点是没有传入链接的节点;然后,它遍历每条路径,同时跟踪原始节点和跳数。最后,外部查询过滤每个路径的最后一个节点。

Demo on DB Fiddle

来源 |交货 |酒花 :----- | :------- | ---: s1 | f1 | 3 s2 | f2 | 4

【讨论】:

    猜你喜欢
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 2019-03-20
    • 2018-10-16
    相关资源
    最近更新 更多