SQL語句中的NOT IN 的優化

2021-07-01 23:29:37 字數 1120 閱讀 8647

sql語句中的in和not in子查詢理解起來很直觀,和實際的業務也很匹配,所有經常被開發人員使用,資料量不大的表還好,如果資料量太大將導致效能問題。

原sql:

select count(distinct t.id)

from task t

where t.tenant_key= 'tp18squme1'

and t.id in(

select entity_id

from share_entry

where entry_type= 'user'

and sid= 8005824118306255410)

and t.id not in(

select distinct s.target_id

from stream s

where s.opt_user= 8005824118306255410

and s.target_id is not null)

and t.creator!= 8005824118306255410

and t.status= 'todo'

由於in和not in會全表掃瞄,所有以上查詢效能很低,耗時4s左右;

優化後的sql:

select count(distinct t.id) from ((select id from task  where tenant_key= 'tp18squme1' and creator!= 8005824118306255410 and status= 'todo') t 

left join (select target_id from stream where opt_user= 8005824118306255410) s on t.id = s.target_id

left join (select entity_id from share_entry where entry_type= 'user' and sid= 8005824118306255410) e on t.id=e.entity_id) 

where s.target_id is null and e.entity_id is not null

用join鏈結查詢代替in和not in查詢可以大大提高效率,優化後的查詢耗時0.2s。

sql優化 in 和 not in 語句

why?in 和 not in 是比較常用的關鍵字,為什麼要盡量避免呢?1 效率低 可以參看我之前遇到的乙個例子 小問題筆記 九 sql語句not in 效率低,用 not exists試試 2 容易出現問題,或查詢結果有誤 不能更嚴重的缺點 以 in 為例。建兩個表 test1 和 test2 c...

SQL 語句中優化方法

整理一下以前的一些用sql語句的習慣。先提乙個概念掃瞄引數 sarg 用於限制搜尋的乙個操作,因為它通常是指乙個特定的匹配,乙個值得範圍內得匹配或者兩個以上條件的 and 連線。1.or 會引起全表掃瞄.如 name 張三 and 5000 符合sarg 而 name zhangsan or 500...

優化SQL語句 in 和not in的替代方案

但是用in的sql效能總是比較低的,從sql執行的步驟來分析用in的sql與不用in的sql有以下區別 sql試圖將其轉換成多個表的連線,如果轉換不成功則先執行in裡面的子查詢,再查詢外層的表記錄,如果轉換成功則直接採用多個表的連線方式查詢。由此可見用in的sql至少多了乙個轉換的過程。一般的sql...