1

I'm trying to insert a new row with the same ID into a simple table but only want to insert if the values are different.

This table is to track price history of an item. The table has the following columns:

id, timestamp, productID, price

I only want to insert a new record if either the product doesn't exist or the product does exist but the price has changed.

Unfortunately I'm having a brain block due to my limited knowledge and would appreciate help in where to turn so I don't have any trials at the code to do this.

Thanks!

2

2 Answers 2

2

you can try something like this:

SET @PRODUCT = 1; # product id
SET @PRICE = 1; # new product price

insert into `t`(`product`, `timestamp`, `price`)
select v.product, now(), v.price
from
(select @PRODUCT as `product`, @PRICE as `price`) as v
left outer join
(select `product`, `price` from `t` where `product`=@PRODUCT order by `id` desc limit 1) as p
on (v.product=p.product)
where
(p.price is null) or
(p.price <> v.price);

so, this statement either insert new row (for new product or new price) or does nothing

Sign up to request clarification or add additional context in comments.

4 Comments

This works perfectly and solves the issues you brought up in your comment earlier with the possibility the price changes back to a previous value. Thanks much!
It seems as there's some kind of issue when the product ID is alphanumeric it returns an unknown column error. I'm trying to figure that out but wanted to also provide feedback to you as well. Ex: SET @PRODUCT = P017428772; # product id
@mika you must be kidding me, of course you should enclose strings into single quotes, like SET @PRODUCT = 'P017428772'; if you don't know that - I suggest you to stop anything you're doing and open any sql book for beginners
Yes, I'm a noob. Sorry. I can do basic stuff but this query was much more complicated than what I am used to so I just missed that. I do appreciate your help!
-1

u need composite primary key

ALTER TABLE products ADD PRIMARY KEY(product,price);

after this query if you insert if the product and price is same in your table returns error with duplicate entry

or it will insert the query even one field value changes

3 Comments

it will not work, for example price was 1 then changed to 2 and then again back to 1
there no such words in the op post he just said "the product does exist but the price has changed. " and @IlyaBursov and he want to store history like price changed 1 today tommorrow it will be 2 just like that my answer is right according to my concern
This table is to track price history of an item track history means that you want to store all price changes

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.