---
title: "MySQL中IN的使用需要当心"
author: "touya"
date: "2009-11-18T09:36:19Z"
tags: []
slug: "mysql-in"
draft: false
lastmod: "2009-11-18T09:36:19Z"
id: 519370
url: "https://touya.iteye.com/blog/519370"
---

在MySQL5中，where语句里使用

(A,B) in ((X1,Y1),(X2,Y2))

索引不会被使用。所以类似

select * from t1, t2 where (t1.a, t2.b) in ((1,2),(2,3))

的语句是无法使用a,b上的索引的，应该改为  
select * from t1, t2 where  (t1.a = 1 and t2.b = 2) or (t1.a = 2 and t2.b = 3)

 

另一个典型例子是:

table1上有一个联合索引(a,b)

select * from table1 where (a=1 and b=2) or (a=2 and b=3);

这是可以用到索引的,而写成in的形式,就不行了,如下所示:

select * from table1 where (a, b) IN ((1,2),(2,3));