595. Big Countries - 大的国家 <easy> -水题

it2026-04-10  5

这里有张 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      | +--------------+-------------+--------------+

select name,population,area from World where area > 3000000 or population > 25000000

注意到有对 or 于 union的讨论 -> StackOverFlow地址:SQL Performance UNION vs OR

select name ,population,area from world where area>3000000 union select name ,population,area from world where population>25000000

对于单个字段来说,用or是没有任何问题的,但是or涉及到多个列的时候,每次select只能选取一个index,如果选择了area,population就需要进行全表扫描,但是使用union就可以解决这个问题,分别使用area和population上面的index进行查询;

union会去除结果集中重复的部分,做到这点需要对结果集进行排序!而这点和table-scan扫描全表一样耗时,但总的来说Sorting is much less costly than the table-scan.

最新回复(0)