5

I am going over a past paper for a database course I am taking and I am stuck on an SQL question

Here is the schema provided

  • Country(name, capital, area), name is the key

  • People(country, population, children, adult) where country refers to the name in Country, population is the total population, and children and adult is the percentage of the children and adult population.

  • Language(country,language,percentage) – for each language spoken in the country, it lists the percentage of the population that speaks the language.

Here is the question:

Write the following query in SQL: Find languages that are only spoken in countries whose total population exceeds 10^7.

This is what I have so far:

SELECT l.language
FROM people p, language l
WHERE l.country = p.country AND
    p.population > 10^7

The bit I am confused about is how to check that there are no other countries which a language is spoken in but the population is less than 10^7.

Any advice? Thanks

4

3 回答 3

4

获取所有语言。从该集合中删除人口 <= 10^7 的国家/地区使用的所有语言。提醒应该是仅在人口 > 10^7 的国家/地区使用的语言。

select language from languages
where language not in (
    select language from languages l
    join people p on l.country = p.country
    where p.population <= 10^7)

这是基于您的设计具有必须在至少一个国家/地区使用每种语言的限制;)

于 2012-04-10T21:12:25.980 回答
1
WITH T 
     AS
     (
      SELECT l.language, 
             p.country, p.population
        FROM people p, language l
       WHERE l.country = p.country
     )
SELECT language
  FROM T
EXCEPT
SELECT language
  FROM T
 WHERE population <= 10000000;

或者:

SELECT language
  FROM language AS l1
 WHERE 10000000 < ( SELECT MIN(p.population)
                      FROM people p, language l
                     WHERE l.country = p.country
                           AND l.language = l1.language );

相似地:

SELECT language
  FROM language AS l1
 WHERE 10000000 < ALL ( SELECT p.population
                          FROM people p, language l
                         WHERE l.country = p.country
                               AND l.language = l1.language );
于 2012-04-11T07:57:34.147 回答
0

我的方法是在每个规模的国家/地区使用不同的语言,然后左加入这两个列表并最终得到仅在人口大于 10^7(或 10000000)的国家/地区使用的语言列表。

;WITH Bigs AS
(
    SELECT DISTINCT l.language
    FROM people p
    INNER JOIN language l ON l.country = p.country
    WHERE p.population > 10000000
)
,Littles AS
(
    SELECT DISTINCT l.language
    FROM people p
    INNER JOIN language l ON l.country = p.country
    WHERE p.population <= 10000000
)
SELECT b.language 
FROM Bigs b
LEFT JOIN Littles l ON l.language = b.language
WHERE l.language IS NULL
于 2020-02-14T20:47:42.423 回答