/*select cd_friend.fid,cd_user.name from cd_friend left join cd_user on cd_user.uid = cd_friend.fid where cd_friend.uid=1312 limit 6 */
這條語句的本意是查詢id為1312 的使用者的好友名字。(用cd_friend.uid 查到cd_friend.fid,再用cd_friend.fid查到cd_user.uid,再到cd_user.name)
這條語句速度非常慢,因為它用了 left join ,同時鎖定了兩張表,而且對另一張表(cd_user)進行了大量的查詢。用explain 檢測,都是範圍ref。
優化方法:
第一種 :select cd_user.name from cd_user ,
(select fid from cd_friend where cd_friend.uid=1312) t1 where cd_user.uid=t1.fid limit 6
這一種可以快一些,因為兩表都分別用了主鍵索引,但還是同時鎖定了兩張表。速度比剛才已經快了很多,它很快找出索要資料。
第二種:
直接給拆成兩條select語句。這樣一定時間內只鎖定一張表,能快速找到資料且釋放掉表。這在併發量多的時候是很重要的。
但這是很多程式設計師的誤區。不願意寫簡單的select語句。其實語句複雜對於系統效能來說並不好。
第三種:
我們經常在select語句上下功夫,幹嘛不在cd_friend表上加一條name欄位呢?這樣,便根本不用連線,也不鎖定多張表,對於資料庫長期使用有很大優勢。
有時候,資料庫冗餘還是必要的。看具體的資料庫情景。在cd_friend庫上,有id,且字段不多,加name是很划算的。
這說明,在資料庫優化上,不能思維定勢。看起來最麻煩的,說不定是最簡單的。
8 2 1 優化select 語句
8.2 優化sql 語句 8.2.1 優化 select 語句 查詢,表現為 select語句,完成了資料庫中的所有查詢操作。調整這些語句具有高優先順序,無論是為了給動態頁面提供亞秒級的響應還是縮短產生大量夜間報表的時間。除了select 語句,調整的技巧同樣適用於 create table as ...
查詢語句(SELECT)的優化建議
從大多數資料庫應用系統的例項來看,查詢 作在各種資料庫 作中所佔據的比重最大,而查詢 作所基於的select語句在sql語句中又是代價最大的語句。size large color red 查詢語句 select 的優化建議 color size color red 1 合理使用索引 where子句中...
基本Select語句
一.基本select語句 select from table 1.select from departments 查詢所有的 2.select department id,location id from departments 指定列 算術表示式 按優先順序 1.select last name,...