MySQL优化使用WHERE子句的子查询?

时间:2014-11-21 08:55:39

标签: mysql

在我的查询中,我使用子查询获得给定产品的第二个最后日期。

这是我的子查询:

LEFT JOIN (SELECT product_id, MAX(offer_date) AS sec_last_date 
           FROM t_offers AS s1  
           WHERE offer_date < (SELECT MAX(offer_date)
                               FROM t_offers 
                               WHERE product_id=s1.product_id)
           GROUP BY product_id) AS t2 ON t2.product_id=p.id 
LEFT JOIN t_offers AS o2 ON o2.product_id=t2.product_id AND 
                            o2.offer_date=t2.sec_last_date

它工作正常,但目前在t_offers表中只有几行。

由于WHERE子句强制MySQL为每个product_id迭代t_offers表,因此数千或数百万行可能无法正常工作。

我怎样才能优化这个子查询?

2 个答案:

答案 0 :(得分:0)

你不能只是对报价日期进行排序,并获得最新的2个:

select product_id, offer_date
from your table
order by offer_Date desc
limit 2

答案 1 :(得分:0)

由于没有为连接使用索引,因此子查询在MySQL中通常不是很好。

然而,尝试使用连接的子查询而不是带有子查询的子查询可能值得: -

LEFT JOIN (SELECT s1.product_id, MAX(s1.offer_date) AS sec_last_date 
           FROM t_offers AS s1  
           INNER JOIN t_offers AS s2
           ON s2.product_id = s1.product_id
           AND s2.offer_date > s1.offer_date
           GROUP BY s1.product_id) AS t2 ON t2.product_id=p.id