595. Big Countries
今天这道题,是个sql语句的题目,选出符合条件的数据;
There is a table World
1 | +-----------------+------------+------------+--------------+---------------+ |
A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million.
Write a SQL solution to output big countries’ name, population and area.
For example, according to the above table, we should output:
1 | +--------------+-------------+--------------+ |
比较简单,select where就可以解决了;
1 | select name, population, area from World where area>3000000 or population>25000000; |
result
Runtime: 196 ms, faster than 82.98% of MySQL online submissions for Big Countries.
结果有点惊讶,这么简单的还会有更好的解决办法?讨论区看了一眼,发现这么一个语句:
1 | SELECT name, population, area FROM World WHERE area > 3000000 UNION SELECT name, population, area FROM World WHERE population > 25000000; |
奇迹出现了??
并没有。。。执行完效率并没有好多少,半斤八两。
这个时候就Google一番,or 和 union差在哪里,以下几篇文章有点参考意义。
- mysql 实战 or、in与union all 的查询效率
- SQL Performance UNION vs OR
- Whether to use UNION or OR in SQL Server Queries
总的来说,性能差异并不是绝对的,都需要针对实际数据进行实际的测试与验证,其中有一点是关键,对于非索引字段,or是肯定胜过union了。