如何优化此查询?

时间:2010-08-18 16:47:25

标签: sql mysql

价格     ID     id_stock     价钱     日期

**stocks**
id
stock_name
active

现在我必须为每个拥有stocks.active=0(我必须通过的日期)的股票设置MAX(prices.date) > 15 days

这是我的查询,但它非常慢!!!

update stocks set stocks.active=0 where stocks.id IN (

SELECT prices.id_stock 
FROM prices
GROUP BY prices.id_stock
HAVING datediff('2010-08-17', MAX( prices.date )) > 15

)

如何优化它?

非常感谢你!

3 个答案:

答案 0 :(得分:7)

UPDATE  stocks
SET     active = 0
WHERE   DATEDIFF('2010-08-17',
        (
        SELECT  MAX(prices.date)
        FROM    prices
        WHERE   id_stock = stocks.id
        )) > 15

prices (id_stock, date)

上创建索引

答案 1 :(得分:0)

我有时会发现重写IN条款,因为EXISTS改善了问题......

UPDATE stocks SET stocks.active=0
    WHERE EXISTS (SELECT prices.id_stock 
                      FROM prices
                      WHERE prices.id_stock = stocks.id
                      GROUP BY prices.id_stock
                      HAVING datediff('2010-08-17', MAX( prices.date )) > 15);

答案 2 :(得分:0)

Update stocks
Set active = 0
Where Exists    (
                Select 1
                From prices
                Where prices.id_stock = stocks.Id
                Having Max(prices.date) < DateAdd( '2010-08-17', Interval -15 Day)
                )