使用无索引的简单MySQL连接

时间:2012-10-11 10:30:24

标签: mysql join

以下查询大约需要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都有索引...

1 个答案:

答案 0 :(得分: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