mysql JOIN優化 清除filesort

2021-09-08 15:56:55 字數 1807 閱讀 8570

(1)顯示inner join 和 隱式inner join

顯示 --> select * from a inner join b on a.mobile = b.mobile;

隱式 --> select * from a inner join b where a.mobile = b.mobile;

10萬資料的查詢用時幾乎相等。

(2)left join / right join 和 inner join

盡量用inner join 避免 外聯結 和 null

在使用外聯結的時候,如 -> select * from a left join b on a.mobile = b.mobile where wherecondition;

如果b中沒有滿足on condition的條件,則會產生一行所有列為null的資料。

在 on condition 匹配階段,where 條件不會被使用。在on condition結束後,where將會被使用,where條件將會從滿足on condition的資料中再檢索一次。

所以,在使用外聯結市,我們要盡量給出盡可能多的匹配滿足條件(即 on condition),減少where字句的檢索。

不建議sql -> select * from a 

left join b on a.mobile = b.mobile

left join c on a.name = c.name

where a.status = 1 and c.status = 1

建議的sql -> select * from a

left join b on a.mobile = b.mobile and a.status = 1

left join c on a.name = c.name and c.status = 1

盡量滿足on condition,而少使用where的條件。

(3)on 條件 和 where 條件的不同

->select * from a left join b on a.mobile = b.mobile on a.name is not null;

將會返回a表的所有記錄 和 b表中滿足 (a.mobile = b.mobile on a.name is not null) 的記錄;

->select * from a left join b on a.mobile = b.mobile where a.name is not null;

將會返回a表中所有記錄 和 b表中滿足 (a.mobile = b.mobile)的記錄,然後 再通過where條件(a.name is not null)對結果進行篩選。

第一條sql語句返回的結果集條數 >= 第二條sql

(4)盡量避免子查詢,而用join

(5)驅動表問題

驅動表定義:執行計畫第一行為驅動表

join mysql會自動選擇 最少行的表做驅動表;

left join 左邊的作為驅動表,盡力用小表驅動大表

不管是你oracle,還是 mysql,優化的目標是盡可能減少join中nested loop的迴圈次數。

多表關聯請盡量使用驅動表或者結束表做order by 這樣可以不適用nested loop 做排序,消除filesort、temporary

更多情況會陸續更新

如「straight_join」強制連線順序技巧

Mysql join語句的優化

mysql4.1開始支援sql的子查詢。這個技術可以使用select語句來建立乙個單列的查詢結果,然後把這個結果作為過濾條件用在另乙個查詢中。使用子查詢可以一次性的完成很多邏輯上需要多個步驟才能完成的sql操作,同時也可以避免事務或者表鎖死,並且寫起來也很容易。但是,有些情況下,子查詢可以被更有效率...

mysql join索引組合優化,效能提公升百倍

組合索引怎麼用比較快 在join的時候需要三個on條件 organization policy type version 乙個where條件 join 條件 where 條件 on a.organization b.organization and a.policy type b.policy ty...

mysql join操作詳解

除了常用的兩個表連線之外,sql mysql join 語法還支援多表連線。多表連線基本語法如下 from table1 inner left right join table2 on condition inner left right join table3 on condition join ...