13518219792

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

MySQL的or/in/union与索引优化

本文缘起自《一分钟了解索引技巧》的作业题。

创新互联专注于猇亭企业网站建设,自适应网站建设,电子商务商城网站建设。猇亭网站建设公司,为猇亭等地区提供建站服务。全流程按需定制开发,专业设计,全程项目跟踪,创新互联专业和态度为您提供的服务

假设订单业务表结构为:

 
 
 
 
  1. order(oid, date, uid, status, money, time, …) 

其中:

假设订单有三种状态:0已下单,1已支付,2已完成

业务需求,查询未完成的订单,哪个SQL更快呢?

 
 
 
 
  1. select * from order where status!=2 
  2. select * from order where status=0 or status=1 
  3. select * from order where status IN (0,1) 
  4. select * from order where status=0 
  5. union all 
  6. select * from order where status=1 

结论:方案1最慢,方案2,3,4都能***索引

但是...

一:union all 肯定是能够***索引的

 
 
 
 
  1. select * from order where status=0 
  2. union all 
  3. select * from order where status=1 

说明:

二:简单的in能够***索引

 
 
 
 
  1. select * from order where status in (0,1) 

说明:

三:对于or,新版的MySQL能够***索引

 
 
 
 
  1. select * from order where status=0 or status=1 

说明:

四、对于!=,负向查询肯定不能***索引

 
 
 
 
  1. select * from order where status!=2 

说明:

五、其他方案

 
 
 
 
  1. select * from order where status < 2 

这个具体的例子中,确实快,但是:

六、作业

这样的查询能够***索引么?

 
 
 
 
  1. select * from order where uid in ( 
  2.          select uid from order where status=0 
  3. select * from order where status in (0, 1) order by date desc 
  4. select * from order where status=0 or date <= CURDATE() 

注:此为示例,别较真SQL对应业务的合理性。

【本文为专栏作者“58沈剑”原创稿件,转载请联系原作者】

戳这里,看该作者更多好文


当前标题:MySQL的or/in/union与索引优化
网页URL:http://cdbrznjsb.com/article/dhsohhp.html

其他资讯

让你的专属顾问为你服务