Chinaunix首页 | 论坛 | 博客
  • 博客访问: 645635
  • 博文数量: 66
  • 博客积分: 15
  • 博客等级: 民兵
  • 技术积分: 2204
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-26 21:43
个人简介

曾就职于阿里巴巴担任Oracle DBA,MySQL DBA,目前在新美大担任SRE。[是普罗米修斯还是一块石头,你自己选择!] 欢迎关注微信公众号 “自己的设计师”,不定期有原创运维文章推送。

文章分类

全部博文(66)

文章存档

2017年(2)

2016年(3)

2015年(7)

2014年(12)

2013年(42)

分类: Mysql/postgreSQL

2014-01-03 16:28:15

关于IN和OR的区别,在High performance mysql 3rd中,有一段话描述的非常清楚:

IN() list comparisons
In many database servers, IN() is just a synonym for multiple OR clauses, because the two are logically equivalent. Not so in MySQL, which sorts the values in the
IN() list and uses a fast binary search to see whether a value is in the list. This is O(log n) in the size of the list, whereas an equivalent series of OR clauses is O(n) in
the size of the list (i.e., much slower for large lists).

对于许多数据库服务器而言,IN()列表不过是多个OR语句的同义词而已,因为IN和OR在逻辑上是等同的。不仅是在MySQL数据库服务器,对于许多其他的数据库服务器使用到IN查询时,都是按照如下方式处理的:
[1] 对IN列表中的数值进行排序。
[2] 对于查询的匹配,每次使用二分查找去匹配IN列表的数值。
所以对于第[2]步,每次比较的算法复杂度大概为O(log n)。相反,对于同样逻辑的OR列表,每次都要遍历,所以OR相应的算法复杂度为O(n)(因此对于遍历非常大的OR列表,会很缓慢!)。

因此,在了解了IN和OR的区别之后,每次优化,我们可以采用如下方式:
1.尽量将能使用IN来代替OR查询。
2.对IN列表中的数据,写SQL的时候排好序,避免MySQL来做这个工作。
阅读(4230) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~