0

I have a price_list table where I store historical prices for each item.

columns are -  id, name, price, start_date, item_id

When a price is changed, a one new row is inserted with a current start_date. (Start_date is a datetime format).

Now I need to select prices of all items for an exact datetime. Problem is that this query is slow (1.058 sec):

SELECT * FROM (SELECT * FROM price_list h WHERE start_date <= '2013-12-15 12:14:18' ORDER BY start_date DESC) a GROUP BY item_id

Very slow is a GROUP BY. Without it it takes 0.075 sec, but each item (item_id) is there a multiple times.

bad: SELECT * FROM price_list h WHERE start_date <= '2013-12-15 12:14:18' ORDER BY item_id, start_date DESC

Please, can this query be rewritten to be quicker?

2
  • Have you tried SELECT id, name, price, start_date, item_id versus using * ?
    – Ryan
    Commented Dec 20, 2013 at 13:40
  • Yes, duration is the same, because I need all columns but I will try LEFT JOIN after group by. Duration goes up when I select name column.
    – Xdg
    Commented Dec 20, 2013 at 13:44

1 Answer 1

-2

Duration goes to 1 sec when I'm selecting name column. But when I use this query, time is only 0.094 sec:

SELECT h.* FROM (SELECT * FROM (SELECT id, item_id FROM price_list x WHERE start_date <= '2013-12-15 12:14:18' ORDER BY start_date DESC) a GROUP BY item_id) b LEFT JOIN price_list h ON h.id = b.id

Thank you, Ryan!

1
  • -1 for still using select * just type in the columns.
    – Zane
    Commented Jun 19, 2014 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.