I need to implement a timetravel view for prices in mysql. The base price table is this:
CREATE TABLE product_price (
product_id INT(11) NOT NULL,
date_valid TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
price DECIMAL(15,4) NOT NULL,
PRIMARY KEY(product_id,date_valid)
);
The idea is that as time passes I select the right valid prices I have entered in advance. Maybe the concept can be clearer later. I need to create a view so that for each product_id I get the latest price. After a while I have found the SELECT that does what I need:
SELECT * FROM (
SELECT product_id,price FROM product_pric
WHERE date_valid <= CURRENT_TIMESTAMP
ORDER BY date_valid DESC
) xx GROUP BY product_id;
In order to create the needed view I understood I cannot use the subselect and need to create one or more intermediate views. Like this:
CREATE VIEW v_product_price_time AS
SELECT product_id,price FROM product_pric
WHERE date_valid <= CURRENT_TIMESTAMP
ORDER BY date_valid DESC
;
CREATE VIEW v_product_price AS
SELECT * FROM v_product_price_time GROUP BY product_id;
What I then get is not the sameas the original query I've written. For example, I populate the table with just two rows:
INSERT INTO product_price (product_id,date_valid,price ) VALUES ( 1,'2013-01-01',41.40 );
INSERT INTO product_price (product_id,date_valid,price ) VALUES ( 1,'2013-01-03',42.0 );
The raw query returns the right data, (1,42.0), but querying the view doesn't. I always get (1,41.40).
Surely I am missing something as I don't know MySQL very well. With another opensource RDBMS I have already done similar stuff, but now I need to cope with MySQL v5.5 and have no way to change it. But the documentation and a few searches in the developers forums didn't lead me to a solution. Any idea on how to solve this? TIA.