bitscn.com
转载自 http://pclevin.blogspot.tw/2011/12/mysql_24.html
mysql執行順序如下
1.from
2.on
3.join
4.where
5.group by
6.with cubeor with rollup
7.having
8.select
9.distinct
10.order by
11.top / limit
如果想要知道自己select語句的效率如何,可以在select之前加上explain 關鍵字
即可得知相關的執行順序及效率分析
如上所列查詢語句有其執行的順序,所以要讓自己的查詢語句提昇效率就必須從這上述各點來下手,在此以例子直接說明
select
*
from
user
join
userprofile as pro
on
user.id = pro.userid
join
useragreement as agr
on
agr.userid = user.id
where
user.birthday = '1984-06-25'
and
pro.local = '員林'
這句sql執行的順序是
1.from user
2.on user.id = pro.userid
3.join userprofile as pro
4.on agr.userid = user.id
5.join useragreement as agr
6.where user.birthday = '1984-06-25'
and
pro.local = '員林'
7.select *
查詢顧名思義如同在電話簿中找尋某人的名字一樣,資料量越大、所知的條件越少查詢所需時間就越長,相對的資料量越少、知道的條件越明確查詢所需的時間就越短。
那麼在這樣的執行順序下我們要怎麼讓資料量縮小以加快速度呢?
照執行順序來走
1.先碰到的就是user這個table,這個table相對於其他兩個table是否資料量最少?以此例討論的確是如此,因為user對userprofile、useragreement都是一對多的關係,當然以user當開頭是一個好開頭。
2.接下來限制條件,以明確的條件來限制、以及少量的資料來比對大量的資料,自然就能保持較佳的查詢效率了。
3.有了明確條件以及少量資料比對的限制,join table效率自然會比較好。
4.5.如上兩點所言,越明確的條件以及少量資料的比對,效率會更好,所以這裡值得注意的是on agr.userid = user.id 以大量的資料去比對少量的資料,這是反其道而行會適得起反降慢速度,on user.id = agr.userid 如果改成這樣就會變成以少量資料去比對大量資料,則又可獲得較佳的效率了。
6.當上述的table都join完成之後,再用where來做整體的條件限制,一直以來都是這麼做的沒錯吧~那就錯大了!!如果條件可以在上面on的時候就限制,資料量便可再更縮小,join出來的table就會很小甚至精準到需求的資料,有時候根本連where都不用寫,那該怎麼寫呢?稍後將會把改完的sql寫在下方給大家參考。
7.join完table,限制條件也結束了,才開始select,此時會將使用者所需要的資料一一列出,大家都會用*來簡便的將一切列出,這也是降低效率的兇手之一,select越明確,越少的欄位會讓整體速度稍微加快,因此在select部份也盡量少濫用*,可獲得較佳的效率
透過上述幾點,將修改後的sql寫出如下︰
select
user.id,
user.username,
pro.phone,
agr.agreementenddate
from
user
join
userprofile as pro
on
user.birthday = '1984-06-25'
and
pro.local = '員林'
and
user.id = pro.userid
join
useragreement as agr
on
agr.userid = user.id
如上所示,在第一次on的條件限制下就將資料量降到最少,甚至精準,如此往後join就會讓資料量大為減少,最後連where都不需要額外限制其他條件,而select部份也只挑出所需的資料就好, 達到最佳的效率
總結︰資料量越小、條件越明確就能達到最好的查詢效率
bitscn.com