Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT when NOT duplicate row?

I simply want to replace (update) DATE, PRICE and OLDPRICE when a price is different than the PRICE in my table where MODEL is unique.

Sample Row Table Data:

DATE        |   MAKE   |   MODEL   |   PRICE   |   OLDPRICE
2012-04-15  | Advance  | DTA-100-X |   400     |   390

There must be a dozen ways to do this but I'm looking for the best solution to use in a MySQL query.

Should I be using:

  1. INSERT INTO..ON DUPLICATE KEY UPDATE
  2. REPLACE INTO..
  3. UPDATE...WHERE PRICE != XXX

Essential syntax would be to UPDATE if the MODEL is the same but the PRICE is different; OLDPRICE becomes PRICE on UPDATE

*UPDATE*

This REPLACES whether price changed or not. I only want updates/replaces if price changed ie, this should NOT update anything given above example, however it does because date is different:

REPLACE INTO MyTable (DATE, MAKE, MODEL, PRICE, OLDPRICE) VALUES ('2012-10-02', 'Advance', 'DTA-100-X', '400', '390')
like image 734
ToddN Avatar asked Dec 12 '25 15:12

ToddN


1 Answers

MySQL has a REPLACE statement specifically for this purpose.

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.

-- http://dev.mysql.com/doc/refman/5.6/en/replace.html

like image 169
Asaph Avatar answered Dec 15 '25 08:12

Asaph