SQL加入/嵌套查询
问题描述:
查询是:显示国家代码和具有大于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)
该表具有了更多的属性,但我们不要求他们马上回答这个查询。
答
首先,您应该明确表示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
答
你有几个选择。下面是一个使用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)
答
标准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
您的公司从事什么类型的数据库? MySql,Oracle,SQL Server? – Ageonix