(持续更新)2020-12-31-SQL(SQLZOO SELECT FROM WORLD)刷题笔记-HK

SQLZOO-SELECT FROM WORLD

小目录

  • Subquery returns more than 1 row的报错解决;
  • 如何表示带有百分号的百分数;
  • 与NULL值做“比较运算”,导致的输出值为空;
  • 找出最值(max、min)的两种方法;

正文

  1. 查询到有多个符合条件的子查询,返回了一个序列,而一个continent变量不可能同时和一堆返回值同时做比较,导致报错

error:Subquery returns more than 1 row
解决方法:在子查询前加入any关键字

select name, continent
from world
where continent = any(
  select distinct continent from world
  where name = 'Argentina' or name = 'Australia'
)
order by name
  1. 带有百分号的整数百分数的表示
    使用round()做个四舍五入的截断,再用concat()拼接%符号;
    其中百分数的精度可以调节,调节round(A,B)的B参数即可。
select name, 
       concat(round(100*population/(select population 
                                      from world 
                                      where name = 'Germany'))
       , '%') as percentage
from world
where continent = 'Europe'
  1. 当比较符号右边的数是NULL时,会没有输出值。

示例:
这段代码没有把gdp=NULL的国家剔除,all()函数会造成gdp会与NULL进行比较,造成输出值丢失;

select name 
from world
where gdp > all(select gdp 
                  from world 
                 where continent = 'Europe' )

加上gdp为非负数的限制,其实是做了去除NULL值的操作,结果就能正常输出了。

select name 
from world
where gdp > all(select gdp 
                  from world 
                 where continent = 'Europe' 
                 && gdp>=0)
  1. 找最值时,
    可以用>=来与自己比较;
SELECT continent, name, area 
FROM world x
WHERE area >= ALL(SELECT area 
                   FROM world y
                  WHERE y.continent=x.continent
                 && area>0)

也可以在where中限定不与自己比较;

SELECT continent, name, area 
FROM world x
WHERE area > ALL(SELECT area 
                   FROM world y
                  WHERE y.continent=x.continent
                 && area>0
                 && x.name <> y.name)

猜你喜欢

转载自blog.csdn.net/weixin_42012759/article/details/112055374