Let's assume we have a table borders(country1,country2) that contains two countries that border each other, eg. (Sweden, Norway), etc. I would like to find all the countries that can be reached from a given country, say Sweden, by using border crossing only.
Here's the first part of my solution:
WITH RECURSIVE border(countryin) AS (
select distinct country
from (select country2::character varying(4) as country
from borders where country1 = 'S'
union
select country1::character varying(4) as country
from borders where country2 = 'S' ) a
UNION
select distinct sp.country::varchar(4)
from (select country1::varchar(4) as country, country2 as n
from borders) sp
join (select country2::varchar(4) as country, country1 as n, countryin as temp
from borders, border) st
on sp.country = st.n
and sp.country in st.temp
where true
)
SELECT distinct countryin, name
FROM border, country
where countryin = code ;
The only thing that I cannot get to work is how to set a constraint so that a specific country exists in the result border table. I tried using and sp.country in st.temp, and several other ways, but I cannot get it to work.
Could some one give me a hint of how this can be solved?
Current Results:
- Right now, I get an error stating " ERROR: syntax error at or near "st" LINE 4: ...s, border) st on sp.country = st.n and sp.country in st.temp "
Desired Results
- List all counties that can be reached recursively using borders starting from 'S'. So, if we have (S,N), (N,R), (R,C), (D,A), we would get: (N,R,C)