title: ERROR: recursive reference in a subquery
body: <p>I have a table 'visits' containing names of 'train', 'country' and 'city'.</p>
  
  <p>Country and city are the country and stations to which train visits.<br>
  Country names are unique however city names can be same.</p>
  
  <p>I want to find out minimum trains for given country names, so as to visit all the stations in those country.</p>
  
  <p>My Approach:</p>
  
  <p>First I will select a train which visits most of the stations of given country/countries, then i need to select a train which visits most of the stations from unvisited stations of given country/countries.</p>
  
  <p>I am trying following CTE but couldn't get rid of error: 'recursive reference in a subquery'.</p>
  
  <pre><code>WITH RECURSIVE
  selectedTrains(name) AS(
      select train
      from visits
      where country in (select country from countries)
      group by train
      order by count(city) DESC
      LIMIT 1
  
      UNION
  
      select train
      from visits
      where country in (select country from countries)
        and city not in (
                select city
                from visits
                where train in (select name from selectedTrains)
                  and country in (select country from countries)
               )
      group by train
      order by count(city) DESC
      LIMIT 1
  ),
  countries(country) AS (
      select country_name
      from country_data
      where country_name in ("USA","China","India")
  )
  SELECT * FROM train_data WHERE train_no IN selectedTrains;
  </code></pre>