Paul
Paul

Reputation: 11746

Issue with duplicate key update with existing values?

I have a DB table that already has an existing value that I don't need to touch. When I try to call my SQL like so:

my table currently looks like this:

id  col1 col2
5   10   

$sql = "INSERT INTO sometable (id, col2) VALUES (5, 20) ON DUPLICATE KEY UPDATE id = 5";

I would expect the table to look like this after my insert:

id  col1 col2
5   10   20

Is there a way to accomplish this without using an update?

Upvotes: 0

Views: 138

Answers (3)

Conrad Frix
Conrad Frix

Reputation: 52645

Assuming id is the key

This

INSERT INTO sometable (id, col2) VALUES (5, 20) 
ON DUPLICATE KEY UPDATE id = 5

Says to update the id field to 5 (UPDATE ID =5). Which would only work if the ID was 5 and makes no sense

What you want is either

INSERT INTO sometable (id, col2) VALUES (5, 20) 
ON DUPLICATE KEY UPDATE col2 = 20;

Or if you want to reference the value it would have been if there was no duplicate then use as Wilken suggested COL2 = VALUES(COl2)

DEMO

Upvotes: 0

gtr1971
gtr1971

Reputation: 2732

Check this out for a good example: MySQL: Insert On Duplicate

Upvotes: 0

Wrikken
Wrikken

Reputation: 70460

Use VALUES()

INSERT INTO sometable (id, col2) VALUES (5, 20)
   ON DUPLICATE KEY UPDATE col2 = VALUES(col2);

Upvotes: 1

Related Questions