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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With