SQL联接/嵌套查询

SQL联接/嵌套查询,sql,join,Sql,Join,查询为:显示两种以上官方语言的国家代码和名称 我的答案是: 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

查询为:显示两种以上官方语言的国家代码和名称

我的答案是:

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) 

此表还有一些属性,但我们现在不需要它们来回答此查询。

首先,您应该明确地加入表。这意味着
JOIN
子句。您的
FROM
子句中应该从不有多个表

接下来,统一命名列。列名中是否使用下划线

因为每个国家只有一个代码(我假设),所以您可以在主查询中按
分组,根本不需要子查询

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

对此,您有多种选择。下面是一个使用
存在的

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)

标准SQL,对所有数据库有效:

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

您使用的是哪种类型的数据库?MySql、Oracle、SQL Server?我是否错过了他指定的数据库类型?你是在假设MySQL吗?我假设存在任何主要的SQL方言。在from子句中放置逗号分隔的表基本上与使用联接相同,至少对于SQL Server是这样,对于Oracle也是这样。你说永远不会,但那根本不是真的。不@ElenaDBA,不是。这绝对不是,而且这是一个可怕的习惯。