SQLZOO练习题(3)
sqlzoo上较难的一些sql查询练习题及其解题思路。
待查询表格样式:
题目1:
找出洲份,當中全部國家都有少於或等於 25000000 人口. 在這些洲份中,列出國家名字name,continent 洲份和population人口。
答案1:
select name, continent, population from world a
where 25000000 >= all(select population from world b
where a.continent = b.continent
and population > 0);
注意如果写成:
select name, continent, population from world a
where all(select population from world b
where a.continent = b.continent
and population > 0)
<= 25000000;
会报错,因为all()方法必须位于where判断语句的右边。
题目2:
有些國家的人口是同洲份的所有其他國的3倍或以上。列出 國家名字name 和 洲份 continent。
答案2:
select name, continent from world a
where population/3 >= all(select population from world b
where a.continent=b.continent
and a.name <> b.name
and population > 0);
思路:
这两题主要涉及子查询和all()的使用。
题1通过在子查询中应用表world b相当于创建了一个world a表的copy,a.continent=b.continent链接两表,子查询中便可以select出父查询所需的所有population,即all(population)。用all the population和25000000进行比较获取查询结果。
题2基本思路同题1相同,不同之处在于要在子查询中加入a.name != b.name来排除all方法中待查询name本身。注意a.name <> b.name不能写在子查询外,否则会无法识别b。此外,也不能写成where population >= 3*all(子查询)的形式,似乎sql中的all()方法不能像python一样进行广播运算。
希望本文对你有所帮助。