MySQL在join子句中选择扫描太多行

时间:2012-09-27 09:03:30

标签: mysql performance join

Oke伙计们,以下一直困扰着我:

我使用下面的查询来选择产品和价格的概述,包括基于另一个表中的字段StartTime的最新结果价格(tresults)。要做到这一点,我想我需要在联接中选择一个子选择。

问题是EXPLAIN函数告诉我MySQL正在扫描所有结果行(225000行)而不使用任何索引。

有什么方法可以加快速度吗?最好通过添加一个WHERE语句让mysql只查看具有相应pID的行。

select p.pID, brandname, description, p.EAN, RetailPrice, LowestPrice, min(price), min(price)/lowestprice-1 as afwijking
from tproducts p
    join ( 
    select Max(tresults.StartTime) AS maxstarttime, tresults.pID
    from tresults
    -- maybe adding a where clause here?
    group by tresults.pID
    ) p_max on (p_max.pID = p.pID)
join tresults res on (res.starttime = p_max.maxstarttime and p.pID = res.pID and res.websiteID = 1)
join tsupplierproducts sp on (sp.pID = p.pID AND supplierID = 1)
join tbrands b on (b.brandID = p.BrandID)
group by p.pID, brandname, description, p.EAN, RetailPrice, LowestPrice

索引位于连接或where子句的所有列上。

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

从您的SQL我假设您仅基于1个供应商(supplierID = 1)列出产品。

最佳做法是在 开始时使用已知过滤器来消除记录,然后使用内部联接加入其他没有过滤器表。

select p.pID, brandname, description, p.EAN, RetailPrice, LowestPrice, min(price), min(price)/lowestprice-1 as afwijking
from 
(select p.pID, p.BrandID p.EAN, Max(t.StartTime) AS maxstarttime
FROM tproducts p INNER JOIN tresults t on supplierID=1 and p.pID=t.pID
group by tresults.pID
) p 
inner join tresults res on (res.websiteID = 1 and p.pID = res.pID and res.starttime = p_max.maxstarttime)
inner join tsupplierproducts sp on (sp.pID = p.pID)
inner join tbrands b on (b.brandID = p.BrandID)
group by p.pID, brandname, description, p.EAN, RetailPrice, LowestPrice

从上面的代码中,我在加入tresults之前从tproducts中删除了所有supplierID!= 1。

让我知道上面的sql是否有帮助,以及EXPLAIN函数的结果是什么

: - )