MySQL優化之in、exists、join


一、inner join 、 in 、exists
1     explain
2     select a.id
3     from application as a
4     where exists(
5       select 1
6       from dispatch_app_history as d
7       where d.bomber_id = 165 and d.application_id = a.id
8     );
 
   
1     explain
2     select a.id
3     from application as a
4     where a.id in (
5       select d.application_id
6       from dispatch_app_history as d
7       where d.bomber_id = 165
8     );
 
    
1     explain
2     select a.id
3     from application as a
4     inner join dispatch_app_history as d on d.application_id = a.id
5     where d.bomber_id = 165;
分析:子查詢需要application_id來關聯外部表application,因為需要application_id字段,所以MySQL認為無法先執行這個子查詢,而對application表進行全表查詢。
結論:子查詢、join查詢具體性能怎么樣需要根據實際情況決定
 
 
二、not in、not exists
    1、執行速度  
1      explain
2      select *
3      from dispatch_app as d
4      where d.application_id not in(
5         select dh.application_id
6         from dispatch_app_history as dh
7      );                       
     
 
    
1      explain
2      select *
3      from dispatch_app as d
4      where not exists (
5         select 1
6         from dispatch_app_history as dh
7         where d.application_id = dh.application_id
8      )
   
  結論:不考慮其他情況,通常情況下not exists的執行效率要高於not in
 
    2、條件中含有null
1      select *
2      from bomber as b
3      where not exists(
4         select 1
5         from dispatch_app_history as d
6         where d.partner_id = b.partner_id
7      )
8      group by b.partner_id;

 
     
1      select *
2      from bomber as b
3      where b.partner_id not in(
4         select distinct d.partner_id
5         from dispatch_app_history as d
6      );
  
結論:對於not in,條件中有null值的時候會直接停止執行返回null結果。對於not exists,條件中有null時會清除null后執行。in、exists的執行與not existst相同
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM