原因:效率低,还有可能出错
方案:使用exists或者not exists替换;但是也不是说完全不能用in或not in这得看你能否确定in这个集合是否存在可确定的集合而且评估集合范围大不大;如何集合你可以确定不大而且里面的值你也确定有值,那么用in或not in是没有问题的!
注意:建表的时候不要默认为null!问题多多!
解释缘由:
t1表 和 t2表 都是150w条数据,600w的样子,都不算大。
但是这样一句查询
select * from t1 where phone not in (select phone from t2) 那么其实这个会从左表取出一条手机号去右表全部600w匹配一遍!那就是相当于150*600
换个写法
select * from t1
where not EXISTS (select phone from t2 where t1.phone =t2.phone) 先匹配出一样的,再匹配不一样的,你想想?是不是更快咯?
而且not in 还可能因为表字段默认null导致匹配数据错误🙅
比如:
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)
执行查询语句:
select id1 from test1
where id1 not in (select id2 from test2)
的结果为🈳️,本来应该是3才对!
原因是:NULL不等于任何非空的值啊!如果id2只有1和2, 那么3<>1 且 3<>2 所以3输出了,但是 id2包含空值,那么 3也不等于NULL 所以它不会输出。