简体   繁体   中英

SQL query - using SELECT to retrieve data from multiple tables

I am using MySQL

I have the following two tables among others (in a database called database_01):

(i) Cities table, which contains names of cities in different countries, along with data such as in which countries these cities are located

Cities (city_id, city_name, country_id, ….)

(ii) Countries table in which I have defined the all the countries in the world along with an id for each country. I believe country_id in the Countries table is a primary key and it is a foreign key in the Cities table. (ie in the Cities table, country_id is used to denote, the country of a city.)

Countries (country_id, country_name,…)

Here the table Countries is kind of a master table as it remains basically static as the list of countries does not change frequently. However, the table Cities is kind of a transaction table, as I always add names of cities to this table, whenever I come across a new city along with the name of the country where this city is found.

I want to produce a report containing the list of Cities along with the name of the Country in which each city is located. (I want to ensure that each city name appears only once in the report, as I may have mistakenly entered the same city twice into the database.)

Eg:-

Country     City
USA         New York
USA         Washington
USA         San Francisco
USA         Chicago
UK          London
UK          Glasgow
UK          Liverpool
Germany     Bonn
Germany     Munich
France      Paris

I ran the following SQL statement

USE database_01;
SELECT countries.country_name
     , DISTINCT cities.city_name
     , FROM cities
     , countries 
 WHERE cities_country_id = countries_country_id   
 ORDER 
    BY country_name;

I am really grateful if someone can very kindly help me.

You can try with below query

select Distinct countries.country_name ,  cities.city_name
from countries left outer join cities on countries.country_id=cities.country_id
order by country_name

note: the distinct is applied on rows but not on individual columns

select distinct cities and Left join countries with cities order by country name

your query is absolutely right if your use left join countries with cities the solution is as follows

  USE database_01;
  SELECT DISTINCT cities.city_name, countries.country_name,
  FROM countries
  LEFT JOIN cities
  WHERE countries.country_id = cities.country_id 
  ORDER BY country_name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM