MySQL優化之in、exists、join
一、inner join 、 in 、exists
1explain 2select a.id 3from application as a 4where exists( 5select 1 6from dispatch_app_history as d 7where d.bomber_id = 165 and d.application_id = a.id 8);
1explain 2select a.id 3from application as a 4where a.id in ( 5select d.application_id 6from dispatch_app_history as d 7where d.bomber_id = 165 8);
1explain 2select a.id 3from application as a 4inner join dispatch_app_history as d on d.application_id = a.id 5where d.bomber_id = 165;
分析:子查詢需要application_id來關聯外部表application,因為需要application_id欄位,所以SQL/">MySQL認為無法先執行這個子查詢,而對application表進行全表查詢。
結論:子查詢、join查詢具體效能怎麼樣需要根據實際情況決定
二、not in、not exists
1、執行速度
1explain 2select * 3from dispatch_app as d 4where d.application_id not in( 5select dh.application_id 6from dispatch_app_history as dh 7);
1explain 2select * 3from dispatch_app as d 4where not exists ( 5select 1 6from dispatch_app_history as dh 7where d.application_id = dh.application_id 8)
結論:不考慮其他情況,通常情況下not exists的執行效率要高於not in
2、條件中含有null
1select * 2from bomber as b 3where not exists( 4select 1 5from dispatch_app_history as d 6where d.partner_id = b.partner_id 7) 8group by b.partner_id;
1select * 2from bomber as b 3where b.partner_id not in( 4select distinct d.partner_id 5from dispatch_app_history as d 6);
結論:對於not in,條件中有null值的時候會直接停止執行返回null結果。對於not exists,條件中有null時會清除null後執行。in、exists的執行與not existst相同