2016-03-01 219 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