18 Star 91 Fork 52

柯基与佩奇 / 数据库SQL实战

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
69.判断是不是大国家.md 3.17 KB
一键复制 编辑 原始数据 按行查看 历史
王鹏 提交于 2020-09-27 10:41 . 69.判断是不是大国家

判断是不是大国家

题目描述

这里有张  World 表

+-----------------+------------+------------+--------------+---------------+ | name | continent | area | population | gdp | +-----------------+------------+------------+--------------+---------------+ | Afghanistan | Asia | 652230 | 25500100 | 20343000 | | Albania | Europe | 28748 | 2831741 | 12960000 | | Algeria | Africa | 2381741 | 37100000 | 188681000 | | Andorra | Europe | 468 | 78115 | 3712000 | | Angola | Africa | 1246700 | 20609294 | 100990000 | +-----------------+------------+------------+--------------+---------------+

Create table If Not Exists World (name varchar(255), continent varchar(255), area int, population int, gdp int)
Truncate table World
insert into World (name, continent, area, population, gdp) values ('Afghanistan', 'Asia', '652230', '25500100', '20343000000')
insert into World (name, continent, area, population, gdp) values ('Albania', 'Europe', '28748', '2831741', '12960000000')
insert into World (name, continent, area, population, gdp) values ('Algeria', 'Africa', '2381741', '37100000', '188681000000')
insert into World (name, continent, area, population, gdp) values ('Andorra', 'Europe', '468', '78115', '3712000000')
insert into World (name, continent, area, population, gdp) values ('Angola', 'Africa', '1246700', '20609294', '100990000000')

如果一个国家的面积超过 300 万平方公里,或者人口超过 2500 万,那么这个国家就是大国家。

编写一个 SQL 查询,输出表中所有大国家的名称、人口和面积。

例如,根据上表,我们应该输出:

+--------------+-------------+--------------+ | name | population | area | +--------------+-------------+--------------+ | Afghanistan | 25500100 | 652230 | | Algeria | 37100000 | 2381741 | +--------------+-------------+--------------+

答案

SELECT
    name, population, area
FROM
    world
WHERE
    area > 3000000 OR population > 25000000
SELECT
    name, population, area
FROM
    world
WHERE
    area > 3000000

UNION

SELECT
    name, population, area
FROM
    world
WHERE
    population > 25000000

方法二 比 方法一 运行速度更快,但是它们没有太大差别。

题解

方法一:使用 WHERE 子句和 OR【通过】 思路

使用 WHERE 子句过滤所有记录,获得满足条件的国家。

算法

根据定义,大国家至少满足以下两个条件中的一个:

面积超过 300 万平方公里。 人口超过 2500 万。 使用下面语句获得满足条件 1 的大国家。

SELECT name, population, area FROM world WHERE area > 3000000

使用下面语句获得满足条件 2 的大国家。

SELECT name, population, area FROM world WHERE population > 25000000

使用 OR 将两个子查询合并在一起。

方法二:使用 WHERE 子句和 UNION【通过】 算法

该方法思路与 方法一 一样,但是使用 UNION 连接子查询。

SQL
1
https://gitee.com/wp950820/database-sql-combat.git
git@gitee.com:wp950820/database-sql-combat.git
wp950820
database-sql-combat
数据库SQL实战
master

搜索帮助