595. Big Countries

来源:互联网 发布:深圳人众软件 编辑:程序博客网 时间:2024/06/07 00:23

问题目标:从名为world表中选择人数在2500万以上或者面积数在300万平方千米的国家。
原答案:

select name,population,area from world where population>25000000 or area>3000000;

看到的最好答案:

SELECT name, population, areaFROM WorldWHERE area > 3000000 UNIONSELECT name, population, areaFROM WorldWHERE population > 25000000

实现思路:
严格来说,当需要扫描两个不同的列时,使用union会更快些(当然使用union all会更快,因为不需要去重。但是union all会不符合要求)
假设我们搜索population和area列,Mysql在一次查询中会使用一个索引,所以它只会使用一个索引而不是两个索引,因此在查询第二列时,将会使用全表扫描而不是搜因。
而使用union时,每个子查询都会使用索引,然后把结果通过union结合。
Why Union is faster than OR?

Strictly speaking, Using UNION is faster when it comes to cases like scan two different column like this.

(Of course using UNION ALL is much faster than UNION since we don’t need to sort the result. But it violates the requirements)

Suppose we are searching population and area, Given that MySQL usually uses one one index per table in a given query, so when it uses the 1st index rather than 2nd index, it would still have to do a table-scan to find rows that fit the 2nd index.

When using UNION, each sub-query can use the index of its search, then combine the sub-query by UNION.
传送门