【MySQL優化】in 和 exists 使用區別

點擊查看MySQL優化系列文章集錦,從頭到尾全部案例均配備源碼,讓你輕鬆看文章,輕鬆實踐
如你不想自己測試案例,可直接看優化總結,瞭解知識點即可

本篇文章沒有實際案例,只說明用法

  • 首先我們先來看倆張表
  • book
  • class

在這裏插入圖片描述

這個時候我們使用in來進行一次查詢 bookid存在class表的數據

select * from book b where bookid in (select id from class);

在這裏插入圖片描述

然後使用exists來進行一次查詢 bookid存在class表的數據

select * from book b where exists (select 1 from class where b.bookid=id );

在這裏插入圖片描述
會發現倆次的數據是一致的,所以下來我們來說一下,在那些情況用in 那些情況用exists

使用場景

  • 當book表的數據集小於class的數據集時 用in 優於exists
  • 當class表的數據集小於book的數據集時 用exists 優於in
select * from book b where bookid in (select id from class);
它的運行方式是這樣的,類似於倆個for循環
for select * from class
for select * from book where book.id=class.id

select * from book b where exists (select 1 from class where b.bookid=id );
exists的運行方式如下
for select * from book
for select * from class where class.id=book.id

以上倆個案例簡單來說 :

  • 如果查詢的兩個表大小相當,那麼用in和exists差別不大。

  • 如果兩個表中一個較小,一個是大表,則子查詢表大的用exists,子查詢表小的用in:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章