sqlzoo习题答案-Select within Select Tutorial

This tutorial looks at how we can use SELECT statements within SELECT statements to perform more complex queries.

namecontinentareapopulationgdp
AfghanistanAsia6522302550010020343000000
AlbaniaEurope28748283174112960000000
AlgeriaAfrica238174137100000188681000000
AndorraEurope468781153712000000
AngolaAfrica124670020609294100990000000
...

8.List each continent and the name of the country that comes first alphabetically.

*******方法一*******

select continent,min(name)
   from world
   group by continent
   order by continent

*******方法二*******

select continent,name from world
group by continent)

(1)为什么group by可以这么用?

*******方法三*******

select continent,name from world x where x.name=(select y.name from world y where y.continent=x.continent order by name limit 1)
continentname
AfricaAlgeria
AsiaAfghanistan
CaribbeanAntigua and Barbuda
EurasiaArmenia
EuropeAlbania
North AmericaBelize
OceaniaAustralia
South AmericaArgentina
解析:给同一个表命名两个别名x和y,今天查了一天资料,都没有查到对应的解释,于是自己在纸上写代码,测试会呈现的结果,并且sqlzoo运行的结果也跟自己预设的一致。

(1)为什么用where y.continent=x.contient,如果不用

select continent,name from world x where x.name=(select y.name from world y order by name limit 1)

执行结果是:

continentname
AsiaAfghanistan

(2)=如果换成in,执行错误



9.Find the continents where all countries have a population <= 25000000. Then find the names of the countries associated with these continents. Show name, continent and population.

*******方法一*******

select name,continent,population from world
where continent in(select continent from world
group by continent
having max(population)<=25000000)

*******方法二*******

SELECT name, continent, population FROM world x  
WHERE 25000000>=ALL (SELECT population FROM world y 
WHERE x.continent=y.continent  
AND population>0) 


10.Some countries have populations more than three times that of any of their neighbours (in the same continent). Give the countries and continents.

select name,continent from world x
where x.population/3> all(select population from world y
where x.continent=y.continent and x.name!=y.name and y.population>0)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值