首页 > 解决方案 > 拥有 2 种或更多官方语言且非官方语言多 2 倍的国家/地区列表

问题描述

我有下一个模型的任务:

数据库模型

接下来的任务是:输出具有两种或两种以上官方语言的国家列表,其中非官方语言的数量至少是官方语言的两倍。

这个任务看起来很简单,但我有一个错误。我接下来尝试了:

SELECT name, countrylanguage.*
FROM country, countrylanguage
WHERE countrycode = code AND isofficial LIKE "t"
GROUP BY isofficial 
HAVING COUNT(*) => 2;

但我只有一个条目回来。

列出所有拥有超过 2 种官方语言的国家:

SELECT country.name
FROM country
JOIN countrylanguage
ON countrycode = code
WHERE isofficial = 't'
GROUP BY country.name
HAVING COUNT(*) >= 2;

但是我应该如何只选择非官方语言多两倍的国家呢?

标签: mysqlsqldatabase

解决方案


内部查询似乎是最简单的方法。从至少有两种官方语言的国家列表开始:

select countrycode, count(1)
from countrylangauge
where isofficial
group by countrycode
having count(1) >= 2

加入类似的查询可以获取非官方语言计数

select official.countrycode, 
       official.number 'Official Langs',
       unofficual.number 'Unofficual Langs'
from (select countrycode, count(1) as number
      from countrylangauge
      where isofficial
      group by countrycode
      having count(1) >= 2
     ) offical
   inner join (select countrycode, count(1) as number
      from countrylangauge
      where not isofficial
      group by countrycode
      -- Since min count of offical is 2, and need double unoffical
      -- then need at lease 4 here
      having count(1) >= 4
     ) unoffical
     on unofficual.countrycode = offical.countrycode
          and unofficual.number >= 2*officual.countrycode

随时加入以country获取有关国家/地区的更多详细信息。


推荐阅读