这里有张 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 |
+-----------------+------------+------------+--------------+---------------+
如果一个国家的面积超过300万平方公里,或者人口超过2500万,那么这个国家就是大国家。
编写一个SQL查询,输出表中所有大国家的名称、人口和地区。
例如,根据上表,我们应该输出:
+--------------+-------------+--------------+
| name | population | area |
+--------------+-------------+--------------+
| Afghanistan | 25500100 | 652230 |
| Algeria | 37100000 | 2381741 |
+--------------+-------------+--------------+
World
表的录入
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')
MySQL解答1
select name, population, area
from World
where area > 3000000 or population > 25000000
耗时:2474 ms
MySQL解答2
select name, population, area
from World
where area > 3000000
union
select name, population, area
from World
where population > 25000000
耗时:2486 ms
心得
平时没有怎么接触过sql语言,所以做这道题基本上是现用现查(还好是从简单的开始做),然后看了网上大神的一些解答,说方法二会快一些。但实际的运行结果是第一种方法更快而且更简洁。(后面感谢评论区大神的指点:第一个是全表扫描,第二种是范围扫描。数据量小的时候看不出,但是一大起来的时候效果就会很明显。)
- sql语言在写的时候会比较像正常的英文,所以看起来更容易理解。但看起来简单,其实里面还有很多细节与技巧还是要好好学习学习。
- 在创建表格时,
Create table
是创建表格,然后用insert
插入数据。 - 在查询时,用
select
选择需要查询的变量;用from
选择需要查询的表格;where
后面接上限制条件即可。
**题目网址:**https://leetcode-cn.com/problems/big-countries/description/