2015-02-11 51 views
0

以下查询非常慢(大约需要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}工作,看到了建议,以提高性能之间的问题更加清晰

+2

如果删除“ORDER BY”,服务器只需要返回符合条件的前12行。如果您包含“ORDER BY”,服务器需要查找符合条件的所有行,对它们进行排序,然后返回排序集的前12行。 – Glenn 2015-02-11 20:24:26

+0

寻找执行计划 – Randy 2015-02-11 20:25:07

+0

@ronin好,很好,我明白了。你认为这将有可能加速嵌套选择,因为这也会放慢速度 – Ford 2015-02-11 20:28:21

回答

1

任何意见将不胜感激。

+0

我希望自己能够提供更清晰的知识,我会阅读EXPLAIN,因为这是我还没学习的东西。谢谢。现在我已经重新执行查询来删除嵌套的select和IFNULL语句(并且在PHP中完成此操作),现在速度要快得多(我只是喜欢在SQL中完成所有操作,但现在我明白了为什么它是一个馊主意....)。谢谢... – Ford 2015-02-11 21:28:43