昨天花了进六七个小时在做一道SQL练习题,也是醉了,下面做个复盘:
题目来自SQLzoo的第九题
9.找出洲份,當中全部國家都有少於或等於 25000000 人口. 在這些洲份中,列出國家名字name,continent 洲份和population人口。
我们分析一下,要找全洲人数都少于25M,1,所有的人口都少于25m;2,每个洲最大值小于25m;3,只要有一个国家人口大于25m,这个洲就能排除;
我写的错误代码1:
SELECT continent,name,population FROM world x
WHERE ALL(SELECT population FROM world y WHERE x.continent =y.continent ) <=25000000
结果报错,问题是:ALL前面需要有应算符,官方文档地址
operand comparison_operator ALL (subquery)
SELECT continent,name,population FROM world x
WHERE 25000000 >= ALL(SELECT population FROM world y WHERE x.continent =y.continent )
so反过来就ok了,我好啰嗦啊,如上。
错误代码2:
SELECT continent,name,population FROM world
WHERE 25000000 >=ALL(SELECT MAX(population) FROM world GROUP BY continent )
问题在于用了max就是求洲最大,再加个ALL,就是要求所有的max都要小于25m才会select出东西来,显然不合理。
把ALL改为ANY行不行,不行,也就只要有一个max小于25m,就全部都selelct出来,明显得出的是错误的。
正确姿势1(用max):
SELECT name,continent,area FROM world x
WHERE 25000000 >=(SELECT max(population) FROM world y WHERE x.continent =y.continent)
姿势2(用ALL):
SELECT name,continent,area FROM world x
WHERE 25000000>=ALL(SELECT population FROM world y WHERE x.continent = y.continent )
姿势3(用HAVING过滤):
SELECT name,continent,area FROM world
WHERE continent IN (
SELECT continent FROM world GROUP BY continent HAVING MAX(population) <= 25000000)
PS:sql语句中where与having的区别
优先:WHERE>GROUP BY>MAX>HAVING
姿势4(最简单,逆向思维,NOT IN):
SELECT name,continent,area FROM world
WHERE continent NOT IN(SELECT DISTINCT(continent) FROM world WHERE population >25000000)
Done!
感谢CCTV,感谢于贵洋,月月鸟大牛们的宝贵建议~