1. 程式人生 > >數據庫優化技巧之in和not in

數據庫優化技巧之in和not in

寫法 exists art null data class -s ack size

在編寫SQL語句時,假設要實現一張表有而另外一張表沒有的數據時。 通常第一直覺的寫法是:

select * from table1 where table1.id not in(select id from table2)

這樣的寫法盡管看起來非常直觀。可是運行的效率會非常低下,在數據量非常大的時候效果尤其明顯,我們推薦使用not exists或左連接來取代。

select a.* from table1 a left join table2 b on a.id=b.id where b.id is null

相同。這樣的方法也適用於in

數據庫優化技巧之in和not in