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)
insertinto test1 (id1) values (1),(2),(3)
insertinto test2 (id2) values (1)