views:

43

answers:

3

I want to use the output of mysqldump to update entries in a live database. I don't want to delete the entries first, simple update statements are fine. Is there a simple way to convert the output of mysqldump which contains INSERT statements to the corresponding UPDATE statements?

It seems such a basic feature, so I'm sure someone created a tool or came up with a method to do it quickly, so people don't have to reinvent the wheel all the time by everyone writing their own scripts for this.

Edit: I'm looking for a generic solution, not one where I have to enumerate the actual table columns by hand. It's a generic problem, so I think there should be a table independent solution for it.

+2  A: 

It's a matter of adding ON DUPLICATE KEY UPDATE clause

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Mchl
Yes, but can it be done automatically? Can mysqldump output such a format? The point is not creating my own script for this, because it's a generic problem, not specific to my database.
Tom
A: 

You could restore the mysqldump data to a new temporary database, then use the multi-table UPDATE syntax to do the update.

UPDATE mydb.mytable AS dest JOIN tempdb.mytable AS origin USING (prim_key)
SET dest.col1 = origin.col1,
    dest.col2 = origin.col2,
    ...

Then drop the temp database.

Bill Karwin
Interesting. I may go with this if there is no other automatic solution to conver inserts to updates. I'm looking for a generic solution which I could use on any table, so I don't have to write down the column names manually.
Tom
A: 

Mchl's answer is valid another easy fix would be change 'INSERT' to 'REPLACE'. Both require a simple search / replace operation (I'd use sed). But if this were being run regularly then it would be a good candidate for replication / using timestamps to create a loader file only containing the modified/new records.

symcbean
Replace deletes the old row first if it exist. Couldn't it cause problem in a live database? I don't want the row to disappear even momentarily. I'd like to update the existing one instead.
Tom
This seems the simplest solution after all even if some rows will disappear momentarily, so I'll go with this.
Tom