我想通过将所有邻国递归添加到已经找到的可达国家(通过仅以“瑞典”开头的集合)来选择可以找到的国家中的所有国家。基本上,我有一个集合S,它在开始时就是集合{Sweden},并从表borders中选择与Country2属性相等(在Country2属性位于S中时)或等于Country2属性(而在Country1属性位于S中。我将S修改为此所选集合。然后,我继续进行此选择,直到没有找到不在S之外的新国家
种类(已编辑)
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;
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。