7

Is there any easy way to update all values after a duplicate key? For example:

INSERT INTO published_books
           SELECT * FROM books
           WHERE book_id = book_id
           ON DUPLICATE KEY UPDATE ?everything?

The table has around 50 columns and updating each would be painful. Any ideas?

luqita
  • 4,008
  • 13
  • 60
  • 93

3 Answers3

5

You can use REPLACE INTO for this purpose:

REPLACE INTO published_books SELECT * from books;
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 2
    Please be aware when using `REPLACE INTO` that it actually deletes and recreates a row with only the information in the insert. It does not update the row as `ON DUPLICATE KEY UPDATE` does. For more info see here: http://code.openark.org/blog/mysql/replace-into-think-twice – George May 22 '13 at 20:11
0

If you can generate the query, you could use something like this (PHP):

$fields = array(
    'field_1',
    'field_2',
    'field_3'
);
$query = '
    INSERT INTO table (
    ' . implode(', ', $fields) . '
    ) SELECT
        -- ...
    ON DUPLICATE KEY UPDATE ';
foreach ($fields as $i => $field) {
    $query .= ($i > 0 ? ', ' : '') . $field . '=VALUES(' . $field . ')';
}
John
  • 177
  • 2
  • 10
-3
INSERT INTO published_books(col1, col2) 
VALUES (’xxx’, ‘yyy’) ON DUPLICATE KEY UPDATE col1 = VALUES(col1)
Taryn
  • 242,637
  • 56
  • 362
  • 405