簡體   English   中英

在 SQL 中使用遞歸 CTE 我必須找到距離德國 3 個邊界的所有國家

[英]Using recursive CTE in SQL I have to find all the Countries that are 3 borders away from Germany

國家 1 國家 2 邊框長度
德國 法國 10000
西班牙 法國 10000
葡萄牙 西班牙 10000
奧地利 德國 10000

從上表我們可以看出,法國和奧地利距離德國只有1個邊界。 西班牙距離德國有2個邊界(因為德國和西班牙有法國作為他們的鄰居,所以我們必須跨越2個邊界才能到達西班牙)。 而葡萄牙距離德國有3個邊界(這里我們必須穿過法國和西班牙才能到達葡萄牙)。

在 SQL 中使用遞歸 CTE 如何找到距離德國 3 個邊界的所有國家?

注意:單個國家/地區可以在任何列中(Country1 列或 Country2 列)。

WITH RECURSIVE THREE_BORDERS_AWAY AS (
    SELECT Country1, Country2, 1 AS BORDERS_AWAY
    FROM borders
    WHERE Country1 = "D" OR Country2 = "D"
    
    UNION ALL
        
    SELECT Country1, Country2, TBA.BORDERS_AWAY + 1
    FROM THREE_BORDERS_AWAY AS TBA
    WHERE BORDERS_AWAY < 3
)
SELECT * FROM THREE_BORDERS_AWAY

這就是我能想到的。

with cte_borders as (
select country1 as from_country, country2 as to_country from borders
union all
select country2 as from_country, country1 as to_country from borders),
cte_germany_neighboors (from_country, to_country, hops) as (
select from_country, to_country, 0
  from cte_borders 
 where from_country = 'Germany' 
union all
select b.from_country, b.to_country, c.hops+1
  from cte_borders b
  join cte_germany_neighboors c
    on c.to_country = b.from_country 
 where c.hops < 4
   and b.from_country <> 'Germany')
select distinct 
       from_country as country,
       min(hops) as hops
  from cte_germany_neighboors
 group by from_country
 order by 2;
country |hops|
--------+----+
Germany |   0|
Austria |   1|
France  |   1|
Spain   |   2|
Portugal|   3|

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM