今天給你們下另外一個性能提高神器-STRAIGHT_JOIN,在數據量大的聯表查詢中靈活運用的話,能大大縮短查詢時間。html
首先來解釋下STRAIGHT_JOIN究竟是用作什麼的:mysql
STRAIGHT_JOIN is similar to JOIN, except that the left table is always read before the right table.
This can be used for those (few) cases for which the join optimizer puts the tables in the wrong order.
意思就是說STRAIGHT_JOIN功能同join相似,但能讓左邊的表來驅動右邊的表,能改表優化器對於聯表查詢的執行順序。sql
接下來咱們舉個例子進行大體的分析:mysql優化
select t1.*
from Table1 t1 inner join Table2 t2 on t1.CommonID = t2.CommonID where t1.FilterID = 1
以上sql大數據量下執行須要30s,是否是很奇怪?明明Table1表的FilterID字段建了索引啊,Table1和Table2的CommonID也建了索引啊。經過explain來分析,你會發現執行計劃中表的執行順序是Table2->Table1。這個時候要略微介紹下驅動表的概念,mysql中指定了鏈接條件時,知足查詢條件的記錄行數少的表爲驅動表;如未指定查詢條件,則掃描行數少的爲驅動表。mysql優化器就是這麼粗暴以小表驅動大表的方式來決定執行順序的。性能
但以下sql的執行時間都少於1s:大數據
select t1.*
from Table1 t1 where t1.FilterID = 1
或優化
select t1.*
from Table1 t1 inner join Table2 t2 on t1.CommonID = t2.CommonID
這個時候STRAIGHT_JOIN就派上用場,咱們對sql進行改造以下:this
select t1.*
from Table1 t1 STRAIGHT_JOIN Table2 t2 on t1.CommonID = t2.CommonID where t1.FilterID = 1
用explain進行分析,發現執行順序爲Table1->Table2,這時就由Table1來做爲驅動表了,Table1中相應的索引也就用上了,執行時間居然低於1s了。spa
分析到這裏,必需要重點說下:code
擴展閱讀:
https://stackoverflow.com/questions/512294/when-to-use-straight-join-with-mysql