1

I have two tables

  • Country with countryid and countryname

  • City with cityid and cityname

I want to extract city names based on the countryid I select.

I'm very new to sql database and please help me with direct query if you can.

Thank you very much.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Varun Barve
  • 323
  • 2
  • 8
  • 18

4 Answers4

3

According to the table structure which you showed, this query is not possible. You need to add a 'country_id' to the cities table so that you know in which country is each city. Once this has been done, your query would be

select cities.cityname, countries.countryname
from cities inner join countries on countries.country_id = cities.country_id
order by countries.countryname, cities.cityname
No'am Newman
  • 6,395
  • 5
  • 38
  • 50
1

First you should have countryid in city table as a country can have many cities. Then you can write.

select A.cityname from city A
where
    A.countryid in (select B.countryid from country B)

Please check this link if you want to find out more.

SQL: Select from one table matching criteria in another?

Community
  • 1
  • 1
Bibek Maharjan
  • 549
  • 2
  • 5
  • 15
0

You have to add a countryid in City table and write the following query

select * from city c left outer join country co on c.countryid=co.countryid;
Balaji Perumal
  • 830
  • 1
  • 6
  • 20
0

You need to have the countryid in the city table.

    SELECT cityid, cityname FROM city WHERE countryid = $CounrtyID
Cyril Joudieh
  • 132
  • 2
  • 15