Getting last price from specific product on MYSQL (faster than this)

て烟熏妆下的殇ゞ 提交于 2019-12-25 00:25:50

问题


I'm grabbing the last price from a specific product, but performance is really slow on over 3 million prices.

Does anyone have a better way of doing this? My server is getting hammered by this slow query.

prices.id is used to store the id of the store in the prices table so I can join it with the stores.id from the stores table.

SELECT prices.id, prices.price, prices.timelog, prices.user_id FROM prices
WHERE prices.id IN (SELECT stores.id FROM stores WHERE city = "miami" )
AND prices.product_id = 1
AND prices.timelog IN 
  (SELECT MAX( lastprice.timelog ) 
   FROM prices AS lastprice 
   WHERE lastprice.id = prices.id AND lastprice.product_id = 1)

回答1:


3 million prices might mean your application could benefit from some denormalisation. (i.e. flag the last price in some manner, remember: write-once, read-many is often worth the overhead of a slower write).

With the current data, worth a try are:

SELECT p1.id, p1.price, p1.timelog, p1.user_id 
FROM prices p1
JOIN stores 
ON stores.id = prices.id
AND stores.city = "miami"
LEFT JOIN prices p2
ON p2.product_id = p1.product_id
AND p2.id = p1.id
AND p2.timelog > p1.timelog
WHERE p1.product_id = 1 AND p2.id IS NULL;

... and another a bit faster option which always escapes me this time of night :)

Keep in mind a lot can change with the proper indexes on tables, so by all means, run an EXPLAIN on the lot.




回答2:


Without seeing the table structures, I think you could do:

select * from prices
join stores on stores.id = prices.id
where stores.city = 'miami' and prices.product = 1
 order by timelog DESC LIMIT 1



回答3:


Try this too:

SELECT prices.id
     , prices.price
     , prices.timelog
     , prices.user_id

FROM prices
    JOIN
      ( SELECT MAX( timelog ) AS lasttimelog
        FROM prices 
        WHERE product_id = 1
      ) AS lastprice
        ON prices.timelog = lastprice.lasttimelog

WHERE EXISTS
    ( SELECT * 
      FROM stores
      WHERE prices.id = stores.id
        AND stores.city = "miami"
    )
  AND prices.product_id = 1

I would guess that an index on (id,product_id,timelog) in products and an index on id or (city,id) in table stores would help the query speed.

It would be better if you run EXPLAIN on the queries and also post the tables structure (fields, indexes, references).



来源:https://stackoverflow.com/questions/5875988/getting-last-price-from-specific-product-on-mysql-faster-than-this

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!