在編寫SQL語句時,如果要實現一張表有而另一張表沒有的數據庫時,通常第一直覺的寫法就是:
select * from table1 where table1.id not in (select id from table2),這種方法雖然很直觀,但是in及not in的寫法經常會影響其執行的效率,對于大數據量時,這個原因經常是性能的瓶頸。在SQL Server中,可以通過左連接的方法來解決,其替代寫法如下:
select a.* from table1 a left join table2 b on a.id=b.id where b.id is null
同理,這個方法也適用于in的情況。