SQLZOO - 嵌套SELECT笔记

本次教程,关于「SELECT 」之中的 「SELECT 」,是更复杂的查询语句。

示例的数据表World:

  1. 查询:人口比俄罗斯多的国家
world(name, continent, area, population, gdp)

示例

SELECT name FROM world
  WHERE population >
     (SELECT population FROM world
      WHERE name='Romania')

答案:

SELECT name FROM world
  WHERE population >
     (SELECT population FROM world
      WHERE name='Russia')
  1. 查询:人均 GDP比英国高的欧洲国家

示例——无

答案

SELECT name
FROM world
WHERE continent='Europe'
AND gdp/population >
        (SELECT gdp/population FROM world
        WHERE name='United Kingdom' )
  1. 查询: 阿根廷和澳大利亚的邻国们

按照上述 2 个国家所在的大洲,选择筛选国家,并依据国名的按照英文字母排序

答案

SELECT name,continent
FROM world
WHERE continent=
        (SELECT continent FROM world
        WHERE name='Argentina' 
         )
OR continent=
        (SELECT continent FROM world
        WHERE name='Australia' 
         )
ORDER BY name ASC;
  1. 查询: 人口数量介于加拿大与波兰之间的国家

答案

SELECT name,population
FROM world
WHERE population>
        (SELECT population FROM world
        WHERE name='Canada' 
         )
AND population<
        (SELECT population FROM world
        WHERE name='Poland' 
         )
  1. 查询: 欧洲其他国家的人口,达到德国人口(欧洲人口最多)的百分之几?

答案

SELECT name, CONCAT(ROUND(100*population/(SELECT population 
FROM world WHERE name='Germany')),'%')
FROM world
WHERE continent='Europe'

ALL子句

查询例子:世界上人口最大的国家是?

SELECT name
  FROM world
 WHERE population >= ALL(SELECT population
                           FROM world
                          WHERE population>0)

因为有些国家的人口数据是 null,所欲需要子查询语句population>0

  1. 查询: 欧洲之外的哪些国家,GDP 指数超过欧洲所有的国家?

答案

SELECT name
FROM world
WHERE continent!='Europe'
AND gdp >= ALL(SELECT gdp
                           FROM world
                           WHERE gdp>0
                           AND continent='Europe' )
  1. 查询: 每个大洲板块,面积最大的国家名称是?

示例

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

答案

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

上述查询语句,使用了correlated or synchronized 语句

  1. 查询: 每个大洲,按照字母排序的第一个国家是?

示例——无

答案

SELECT continent, name
FROM world x
WHERE name= 
(SELECT name FROM world y
WHERE y.continent=x.continent
ORDER BY name ASC LIMIT 1)

注意:LIMIT 1子句

  1. 查询: 哪个大洲里,所有国家的人口总数都小于25000000?

示例——无

答案

SELECT name, continent, population 
FROM world x
WHERE NOT EXISTS (                 
   SELECT *
   FROM world y
   WHERE y.continent = x.continent 
   AND y.population > 25000000     
   );

注意:LIMIT 1子句

  1. 查询: 哪些国家的人口比同一大洲的所有国家的人口的三倍以上?

示例——无

答案

SELECT name, continent
FROM world AS x
WHERE population/3 > ALL (
  SELECT y.population
  FROM world AS y
  WHERE x.continent = y.continent
  AND x.name != y.name);

注意:LIMIT 1子句

你可能感兴趣的:(SQLZOO - 嵌套SELECT笔记)