595. Big Countries

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

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

看到的最好答案:

SELECT name, population, area
FROM World
WHERE area > 3000000 
UNION
SELECT name, population, area
FROM World
WHERE 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.
传送门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值