資料庫最佳化技巧之in和not in

來源:互聯網
上載者:User

在編寫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

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.