以下查詢非常慢(大約需要1秒),但僅搜索大約2500條記錄(+內連接表)。 如果我刪除ORDER BY,查詢運行時間少得多(0.05或更少) 或者如果我刪除部分嵌套選擇下面的「#用於選擇沒有ProfilePhoto指定」它也運行快,但我需要兩個包括這些。瞭解爲什麼這個查詢很慢
我有索引(或主鍵):tPhoto_PhotoID,PHOTOID,p.Enabled,客戶ID,tCustomer_CustomerID,ProfilePhoto(布爾),u.UserName,e.PrivateEmail,m.tUser_UserID,啓用,活動,m.tMemberStatuses_MemberStatusID ,e.tCustomerMembership_MembershipID,e.DateCreated (做我有太多的指標我的理解是添加它們無論我使用WHERE或ON?)
查詢:
SELECT e.CustomerID,
e.CustomerName,
e.Location,
SUBSTRING_INDEX(e.CustomerProfile,' ', 25) AS Description,
IFNULL(p.PhotoURL, PhotoTable.PhotoURL) AS PhotoURL
FROM tCustomer e
LEFT JOIN (tCustomerPhoto ep INNER JOIN tPhoto p ON (ep.tPhoto_PhotoID = p.PhotoID AND p.Enabled=1))
ON e.CustomerID = ep.tCustomer_CustomerID AND ep.ProfilePhoto = 1
# used to select where no ProfilePhoto specified
LEFT JOIN ((SELECT pp.PhotoURL, epp.tCustomer_CustomerID
FROM tPhoto pp
LEFT JOIN tCustomerPhoto epp ON epp.tPhoto_PhotoID = pp.PhotoID
GROUP BY epp.tCustomer_CustomerID) AS PhotoTable) ON e.CustomerID = PhotoTable.tCustomer_CustomerID
INNER JOIN tUser u ON u.UserName = e.PrivateEmail
INNER JOIN tmembers m ON m.tUser_UserID = u.UserID
WHERE e.Enabled=1
AND e.Active=1
AND m.tMemberStatuses_MemberStatusID = 2
AND e.tCustomerMembership_MembershipID != 6
ORDER BY e.DateCreated DESC
LIMIT 12
我也有類似的查詢,但他們跑得快得多。直到我們獲得的MySQL客戶端在其他查詢etc..Try EXPLAIN {YourSelectQuery}
工作,看到了建議,以提高性能之間的問題更加清晰
如果刪除「ORDER BY」,服務器只需要返回符合條件的前12行。如果您包含「ORDER BY」,服務器需要查找符合條件的所有行,對它們進行排序,然後返回排序集的前12行。 – Glenn 2015-02-11 20:24:26
尋找執行計劃 – Randy 2015-02-11 20:25:07
@ronin好,很好,我明白了。你認爲這將有可能加速嵌套選擇,因爲這也會放慢速度 – Ford 2015-02-11 20:28:21