Re: How can I improve the performance of this kind of query?
Hmmm...
SELECT stocks.stock_id AS stock_id,
stocks.symbol AS symbol,
stocks.name AS stock_name,
A.`close` AS close_price,
A.price_date AS price_date
FROM etf_stocks LEFT JOIN stocks ON etf_stocks.stock_id =
stocks.stock_id
LEFT JOIN stockprices A ON stocks.stock_id = A.stock_id
/*This is grabbing the most recent date for that STOCK_ID from an
aliased STOCKPRICES table and using that as a criteria.
It's the same as using a max, but I've found on MySQL that MAX in a
sub-query sucks, and an order/limit doesn't - no idea why
*/
where A.price_date = (select price_date from stockprices A2 where
A2.stock_id = A.stock_id order by price_date desc limit 1)
AND etf_id = id;
An index on stock_id and possibly on stock_id,price_date would
probably in this case to make the subquery run faster.
|