面試官:為什么要盡量避免使用 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,狀態(tài) 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-
最近有一些小伙伴,讓我?guī)兔φ乙恍?nbsp;面試題 資料,于是我翻遍了收藏的 5T 資料后,匯總整理出來,可以說是程序員面試必備!所有資料都整理到網盤了,歡迎下載!

面試題】即可獲取