in not in 不足
IN 和 NOT IN 是比较常用的关键字,为什么要尽量避免呢?
1、效率低
项目中遇到这么个情况:
t1表 和 t2表 都是150w条数据,600M的样子,都不算大。
但是这样一句查询
select * from t1 where phone not in (select phone from t2)
phone在两个表都建了索引,字段类型也是一样的。not in 是不能命中索引的。。。。
改成 NOT EXISTS 之后查询 20s ,效率真的差好多。
select * from t1
where not EXISTS (select phone from t2 where t1.phone =t2.phone)
2、容易出现问题,或查询结果有误 (不能更严重的缺点)
以 IN 为例。建两个表:test1 和 test2
create table test1 (id1 int)
create table test2 (id2 int)
insert into test1 (id1) values (1),(2),(3)
insert into test2 (id2) values (1),(2)
insert into test2 (id2) values (NULL)
我想要查询,在test2中存在的 test1中的id 。使用IN的一般写法是:
select id1 from test1
where id1 in (select id2 from test2)
结果啥数据没有
原因是:NULL不等于任何非空的值啊!如果id2只有1和2, 那么3<>1 且 3<>2 所以3输出了,但是 id2包含空值,那么 3也不等于NULL 所以它不会输出。
如何优化上述数据呢
用 EXISTS 或 NOT EXISTS 代替
select * from test1
where EXISTS (select * from test2 where id2 = id1 )
select * FROM test1
where NOT EXISTS (select * from test2 where id2 = id1 )
2、用JOIN 代替
select id1 from test1
INNER JOIN test2 ON id2 = id1
select id1 from test1
LEFT JOIN test2 ON id2 = id1
where id2 IS NULL
in和not in 啥时候用呢
如果是确定且有限的集合时,可以使用。如 IN (0,1,2)。