tags:

views:

65

answers:

1

I've just checked out the ON DUPLICATE KEY UPDATE for MySQL.

Here is an example query.

$query = 'INSERT INTO `activities`
                  (`id`,
                   `hole_id`,
                   `name_id`,
                   `start_depth`,
                   `end_depth`,
                   `start_time`,
                   `end_time`
                  ) VALUES (
                :id,
                :hole_id,
                :name_id,
                :start_depth,
                :end_depth,
                :start_time,
                :end_time
            ) ON DUPLICATE KEY UPDATE
               `id` = :id,
               `hole_id` = :hole_id,
               `name_id` = :name_id,
               `start_depth` = :start_depth,
               `end_depth` = :end_depth,
               `start_time` = :start_time,
               `end_time` = :end_time
            ';

There is a lot of repetition there obviously.

Is there a way to say "insert, or if exists use the existing information to update".

I've looked at REPLACE, and it says it inserts and deletes if neccessary. The docs say to insert or update to use the method I've used above.

So can I eliminate doubling up of all that update info?

+3  A: 

You can use the VALUES() function to refer to the value of a column rather than repeating the value in the ON DUPLICATE KEY portion. See: http://dev.mysql.com/doc/refman/5.1/en/miscellaneous-functions.html#function_values.

For example:

$query = 'INSERT INTO `activities`
              (`id`,
               `hole_id`,
               `name_id`,
               `start_depth`,
               `end_depth`,
               `start_time`,
               `end_time`
              ) VALUES (
            :id,
            :hole_id,
            :name_id,
            :start_depth,
            :end_depth,
            :start_time,
            :end_time
        ) ON DUPLICATE KEY UPDATE
           `id` = VALUES(id),
           `hole_id` = VALUES(hole_id),
           `name_id` = VALUES(name_id),
           `start_depth` = VALUES(start_depth),
           `end_depth` = VALUES(end_depth),
           `start_time` = VALUES(start_time),
           `end_time` = VALUES(end_time)
        ';
lrm
Interesting, and I appreciate your answer, but it still looks like the same amount of SQL. Ideally, I'd like to half it. But I realise SQL abstractions sometimes make life difficult. +1
alex
I don't believe you can reduce the size of the query. However, by using VALUES() you are reducing your repetition by only placing the values for the record in once place within the query.
lrm
@Irm Okay, thank you again.
alex