2016-03-01 148 views
0

查询是:显示国家代码和具有大于2种的官方语言SQL加入/嵌套查询

我的回答是:

select 
    c.country_name, 
    cl.countrycode 
from 
    country c, 
    countrylanguage cl 
where 
    c.code=cl.countrycode and c.code IN 

    (select code 

     from countrylanguage 
     where cl.isOfficial='T' 
     group by cl.countrycode 
     having count(cl.isOfficial)>2 
    ); 

的问题是,如果任何一个国家有3个官方语言,多数民众赞成大于2,即多次相同的输出的显示如同 ZWE津巴布韦 ZWE津巴布韦 ZWE津巴布韦

但只有一个 我需要有两个表克伊芬如下

CountryLanguage (CountryCode, Language ,IsOfficial ,Percentage) 

Country (Code ,country_Name) 

该表具有了更多的属性,但我们不要求他们马上回答这个查询。

+1

您的公司从事什么类型的数据库? MySql,Oracle,SQL Server? – Ageonix

回答

0

首先,您应该明确表示JOIN。这意味着JOIN子句。你的FROM条款应该是从来没有有史以来有多个表中。

接下来,一致地命名您的列。你在列名中使用下划线还是不使用?

由于每个国家只有一个代码(我假设),您可以在主查询中只需GROUP BY - 根本不需要子查询。

SELECT 
    C.country_name, 
    CL.country_code 
FROM 
    Country C 
INNER JOIN CountryLanguage CL ON CL.country_code = C.code 
GROUP BY 
    C.country_name, 
    CL.country_code 
HAVING 
    COUNT(*) > 2 
+1

我错过他指定他的数据库类型的位置吗?你在假设MySQL吗? – Ageonix

+0

我假设存在任何主要的SQL方言。 –

+1

在from子句中放置逗号分隔表基本上与使用连接相同,至少对于SQL Server而言,至少对于Oracle而言是相同的 – ElenaDBA

0

你有几个选择。下面是一个使用exists

select code, country_name 
from country c 
where exists (
    select 1 
    from countrylanguage cl 
    where c.code = cl.countrycode 
    group by cl.code 
    having count(*) > 2) 
0

标准SQL,适用于所有DB:

select 
    country.countrycode, 
    country.country_name 
from 
    country 
    join countrylanguage on country.code = countrylanguage.countrycode 
where 
    countrylanguage.isofficial = 'T' 
group by 
    country.countrycode, 
    country.country_name 
having 
    count(*) > 2