mysql in与or查询

关于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来作这个工做mysql