SQL...updating product prices but keeping previous values
The best way to go about this while keeping a tidy database with easily maintainable and readable data would be to take what @KishorSubedi said in the comment and create a log table.
When you update your price in your Products Table, store the old price, along with its date and ID in the Log Table then when you need to look up all the records for that product you can JOIN the Log Table in your query.
Log Table| ProductID | Price | Date || 27 | $300 | 02.1.2013 || 27 | $400 | 03.1.2013 |
This way you can have a nice and neat Products table that is not cluttered with multiples of the same product, and an unobtrusive log table that is easily accessible.
Hope this gives you some guidance on building your site and database.
If you want to keep the old values I would suggest saving them in a seperate table and to use the INSERT
statement. You are always adding a new row, so you can not bypass an insert
or select into
or similar statement.
Table structure:
Items------------------------------Id primarykeyNamePrice------------------------------Id primarykey autoincrementItemId indexAddDate indexPrice
Now when you scrape the web you will just insert the new price in the Price
table. If you want to select all the prices for an item you can use
SELECT Items.Id ,Items.Name ,Price.Price ,Price.AddDateFROM ItemsLEFT JOIN PriceON Items.Id=Price.ItemIdWHERE Items.Id='27'ORDER BY Items.Name ASC, Price.AddDate ASC
And if you just want the latest or current price, you can use
SELECT Items.Id ,Items.Name ,P1.Price ,P1.AddDateFROM ItemsLEFT JOIN Price P1ON Items.Id=Price.ItemIdLEFT JOIN Price P2ON P1.ItemId=P2.ItemIdAND P1.Id<P2.IdWHERE Items.Id='27'AND P2.Id IS NULL