Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update if exist, insert if not exist [duplicate]

Possible Duplicate:
How do I update if exists, insert if not (aka upsert or merge) in MySQL?

I have program that can do batch updating price for booking engine.

example user input for to do update batch the price is like this

$dateStart = '2012-12-01';
$dataEnd = '2012-12-31';
$hotelId = 1;
$price = 300000;

And database is like this

id | date       | hotelId | price
1  | 2012-12-01 | 1       | 100000

How should the MySQL Query, to do batch update and insert with condition if date and hotelId is already exist then do update, but if not exist do insert?

I understand if doing looping day by day and checking if data exist or not in PHP will be really spend much memory.

for($i=1; $i<=31; $i++){...}

I'm looking solution how it can be done with single/any mysql query that can save computer resource.

like image 913
GusDeCooL Avatar asked Dec 27 '12 17:12

GusDeCooL


People also ask

How do I use insert on duplicate key update?

The Insert on Duplicate Key Update statement is the extension of the INSERT statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing row occurs.

How do you avoid duplicate insertion?

Note − Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.


1 Answers

Use the INSERT ... ON DUPLICATE KEY UPDATE ... statement.

It will require that you have a UNIQUE or PRIMARY compound index on the date and hotelId columns so that the DUPLICATE KEY condition is triggered.

like image 81
Ted Hopp Avatar answered Oct 16 '22 05:10

Ted Hopp