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.
传送门
- 595. Big Countries
- [leetcode]595. Big Countries
- 595. Big Countries
- 595. Big Countries
- 【LeetCode】595. Big Countries
- 595. Big Countries
- 595. Big Countries
- 595. Big Countries
- [Leetcode]595.Big Countries
- 595. Big Countries
- [LeetCode] 595.Big Countries
- Big Countries
- LeetCode-595 Big Countries
- 2.leetCode595: Big Countries
- Big Countries [LeetCode 595]
- LeetCode——595. Big Countries(mysql)
- leetcode 595. Big Countries(SQL,最简单的leetcode题目)38
- Countries
- PowerManager规则
- volatile关键字
- Android的画布,具体数据去画
- linux学习第二十九篇:linux网络相关,防火墙:firewalld和netfilter,netfilter5表5链介绍,iptables语法
- bind 一个存在的service的流程
- 595. Big Countries
- android 利用superuser编写使用root权限的app
- extern C的作用详解
- JNI的两种方式
- Android开发调试性能分析工具:dumpsys
- 云计算、虚拟化、容器化杂谈
- 跟踪Android callback 调用堆栈
- Python 从入门到放弃(一)
- lseek的与O_APPEND的冲突