使用count(*)和内部联接时查询缓慢

时间:2019-03-04 20:51:08

标签: mysql sql

我的查询大约需要5秒钟才能运行。它返回近5000条记录。

SELECT 
    c.CompanyID, 
    c.CompanyName, 
    psr.PartnerSRFName, 
    psr.PartnerSRLName, 
    be.MonthlyFee, 
    (
        SELECT Count(*) 
        FROM Units
        INNER JOIN Properties ON Units.PropertyID = Properties.PropertyID
        WHERE Properties.CompanyID = c.CompanyID
    ) TotalUnits
FROM Company c
LEFT JOIN Partner_SalesRep_CompanyMap psrcm ON c.CompanyID = psrcm.CompanyID
LEFT JOIN Partner_SalesReps psr ON psrcm.Partner_SalesRepsID = psr.AssignedID
LEFT JOIN Billing_Exemption be ON be.CompanyID = c.CompanyID
WHERE c.LeadSourceCompanyID = 1 AND Active = 1

如果我删除Select Count(*) ...,它的运行速度非常快,但是我需要这些数据。有没有办法改善这个查询?

谢谢

2 个答案:

答案 0 :(得分:3)

戈登·利诺夫(Gordon Linoff)推荐的索引是必须具备的。

您可能要做的另一件事是将计算从内联查询移动到联接的子查询。这可能使RDBMS可以优化查询,因为现在很明显,不需要为每条记录重复计算(只有model.X = Var(model.S) 的不同值才有所不同):

CompanyID

另一种选择是将子查询与外部查询合并(通过向外部查询添加更多联接),打开整个外部查询的聚合,并使用表SELECT c.CompanyID, c.CompanyName, psr.PartnerSRFName, psr.PartnerSRLName, be.MonthlyFee, COALESCE(x.TotalUnits, 0) TotalUnits FROM Company c LEFT JOIN Partner_SalesRep_CompanyMap psrcm ON c.CompanyID = psrcm.CompanyID LEFT JOIN Partner_SalesReps psr ON psrcm.Partner_SalesRepsID = psr.AssignedID LEFT JOIN Billing_Exemption be ON be.CompanyID = c.CompanyID LEFT JOIN ( SELECT Properties.CompanyID, COUNT(*) TotalUnits FROM Units INNER JOIN Properties ON Units.PropertyID = Properties.PropertyID GROUP BY Properties.CompanyID ) x ON x.CompanyID = c.CompanyID WHERE c.LeadSourceCompanyID = 1 AND Active = 1 或{中的唯一列{1}}进行计数。我并不喜欢这个,因为通常情况下,聚合越早,效率越高。

答案 1 :(得分:2)

对于此子查询:

(Select Count(*)
 From Units u join
      Properties p
      on u.PropertyID = p.PropertyID
 Where p.CompanyID = c.CompanyID
) as TotalUnits

您要在properties(companyid, propertyid)units(propertyid)上建立索引。