面试官:为什么要尽量避免使用 IN 和 NOT IN?大部分人都会答错!
1、效率低
select * from t1 where phone not in (select phone from t2)
select * from t1
where not EXISTS (select phone from t2 where t1.phone =t2.phone)
2、容易出现问题,或查询结果有误 (不能更严重的缺点)
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)
select id1 from test1
where id1 in (select id2 from test2)
select id1 from test1
where id1 in (select id1 from test2)
select id1 from test2
是一定会报错: 消息 207,级别 16,状态 1,第 11 行 列名 'id1' 无效。insert into test2 (id2) values (NULL)
select id1 from test1
where id1 not in (select id2 from test2)
跑题一句:建表的时候最好不要允许含空值,否则问题多多。想成为架构师,这份架构师图谱建议看看,少走弯路。
HOW?
1、用 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
-End-
最近有一些小伙伴,让我帮忙找一些 面试题 资料,于是我翻遍了收藏的 5T 资料后,汇总整理出来,可以说是程序员面试必备!所有资料都整理到网盘了,欢迎下载!
面试题
】即可获取