O
O
Omniverse2016-04-15 02:12:49
MySQL
Omniverse, 2016-04-15 02:12:49

SQL query. How to link data from three tables?

Hello.
Continuation of a question
There is a table country with fields Code (records of type: RUS, BEL, KAZ) and Region (records of type: Asia, Europe, Africa). There is also a city table with fields ID, Name (records like: Moscow, Minsk, Beijing) and CountryCode (records like: RUS, BEL, KAZ).
The third table is countrylanguage with the fields CountryCode(same as in city) and Language(language name)
How to display the resulting table, where in one column there are names of regions, in the second - the number of cities in each region, in the third - the number of languages?
Well, that is:
Region | cities | Languages
​​---------+--------+----------
Europe |... 100 |.....50
Africa ..|... .. 80 | .... 70
Asia .....|... 300 | ...110

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilya, 2016-04-15
@rpsv

SELECT a.Region,  COUNT(b.id) as cities, COUNT(c.id) as languages
FROM country AS a
  INNER JOIN city AS b ON a.Code = b.CountryCode
  INNER JOIN countrylanguage AS c ON a.Code = c.CountryCode
GROUP BY country.Region

In general, linking is better done by identifiers

W
WebDev, 2016-04-15
@kirill-93

SELECT a.Region,  COUNT(b.Name) as cities, COUNT(c.id) as languages
FROM `country` as a 
LEFT JOIN city as b 
LEFT JOIN CountryCode as c
ON a.Code = b.CountryCode 
GROUP BY a.Region

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question