0

下面的查询大约需要 0.3 秒。为什么?我该如何解决。应该不会花这么长时间...

SELECT tshops.OfficialName
 , tresults.StartTime
 , tresults.Price
 , tresults.shopID
FROM
 tresults
INNER JOIN tshops
ON tshops.shopID = tresults.shopID
WHERE
  tresults.pID = 15
  AND tresults.websiteID = 1
  AND tresults.StartTime = (SELECT max(tresults.StartTime) AS maxstarttime
                        FROM
                          tresults
                        WHERE
                          tshops.shopID = tresults.shopID
                          AND tresults.pID = 15
                          AND tresults.websiteID = 1)
ORDER BY
  tresults.Price DESC

解释结果:

1, PRIMARY, tshops, ALL, PRIMARY, , , , 203, Using temporary; Using filesort
1, PRIMARY, tresults, eq_ref, PRIMARY,idxPID,idxWebsite,idxStartTimeASC,idxStartTimeDESC,fk_shopID, PRIMARY, 20, func,const,pricegrabber.tshops.shopID,const, 1, Using where
2, DEPENDENT SUBQUERY, tresults, ref, idxPID,idxWebsite,fk_shopID, fk_shopID, 4, pricegrabber.tshops.shopID, 891, Using where; Using index

这样就完成了对 tshops 的全表扫描。但为什么?两个表中都有关于 shopID 的索引...

4

1 回答 1

0

我怀疑引用外部选择的子选择是令人困惑的事情。

尝试使用 shopID 上的 GROUP BY 对子选择进行连接。通常我希望 MySQL 会优化一些东西来做到这一点,但值得一试。

像这样的东西(请原谅任何错别字)

SELECT tshops.OfficialName
 , tresults.StartTime
 , tresults.Price
 , tresults.shopID
FROM  tresults
INNER JOIN tshops
ON tshops.shopID = tresults.shopID
INNER JOIN (SELECT shopID, MAX(tresults.StartTime) AS MaxStartTime 
            FROM tresults 
            WHERE tresults.pID = 15 
            AND tresults.websiteID = 1 
            GROUP BY shopID) Sub1
ON tresults.StartTime = Sub1.MaxStartTime
WHERE
  tresults.pID = 15
  AND tresults.websiteID = 1
ORDER BY
  tresults.Price DESC
于 2012-10-11T10:48:30.893 回答