用 EXISTS 或 NOT EXISTS 用法

项目中遇到这么个情况:

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)

用 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 )
原文地址:https://www.cnblogs.com/gylhaut/p/9212073.html