开发者社区> 问答> 正文

查找所有可以通过递归选择找到的条目

我想通过将所有邻国递归添加到已经找到的可达国家(通过仅以“瑞典”开头的集合)来选择可以找到的国家中的所有国家。基本上,我有一个集合S,它在开始时就是集合{Sweden},并从表borders中选择与Country2属性相等(在Country2属性位于S中时)或等于Country2属性(而在Country1属性位于S中。我将S修改为此所选集合。然后,我继续进行此选择,直到没有找到不在S之外的新国家

展开
收起
游客ufivfoddcd53c 2020-01-04 17:13:55 872 0
1 条回答
写回答
取消 提交回答
  • 种类(已编辑)

    create table borders(
        Country1 varchar(100),
        Country2 varchar(100)
    );
    insert into borders(Country1,Country2)
    values
    ('Sweden','Finland'),
    ('Norway','Sweden'),
    ('Norway','Finland'),
    ('Norway','Russia'),
    ('Russia','Ukraine'),
    ('Russia','Finland'),
    ('Russia','China'),
    ('Canada','United States')
    ;
    
    WITH RECURSIVE neighbours AS (
        -- start with 'Sweden' if any neighbour of it exists
        SELECT DISTINCT 'Sweden' as Name, ARRAY[cast('Sweden' as varchar)] as path
        FROM borders b 
        WHERE 'Sweden' IN (b.Country1, b.Country2)
        --
        UNION ALL
        SELECT 
          CASE WHEN nb.Name = b.Country1 THEN b.Country2 ELSE b.Country1 END, 
          path || CASE WHEN nb.Name = b.Country1 THEN b.Country2 ELSE b.Country1 END
        FROM borders b
        JOIN neighbours nb ON nb.Name IN(b.Country1, b.Country2) 
              AND NOT(b.Country1 = ANY(path) AND b.Country2 = ANY(path))
    )
    SELECT DISTINCT Name
    FROM neighbours;
    
    2020-01-04 17:14:15
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载