Let's say I have a table Foo
. This table has the columns ID
and UniqueCode
defined like so:
CREATE TABLE Foo
(
ID BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
UniqueCode VARCHAR(255) NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT UNIQUE(UniqueCode)
);
Now let's say I have the following query:
INSERT INTO Foo (ID, UniqueCode) VALUES ($id, $uniqueCode)
ON DUPLICATE KEY UPDATE UniqueCode = $uniqueCode;
In this scenario, I would like ON DUPLICATE KEY UPDATE
to only fire if the ID
is a duplicate, but NOT when UniqueCode
is a duplicate. I realize this will cause a unique key constraint error. My first thought is to first check and see if $uniqueCode
is in use, and change it if it is. Is there any way I can specify this in the MySQL statement instead?
EDIT: In pseudocode what I would like to have is:
INSERT INTO Foo(ID, UniqueCode) VALUES ($id, $uniqueCode)
ON DUPLICATE KEY UPDATE
(
IF (duplicate key is ID)
update uniqueCode = $uniqueCode where ID = $id
ELSE // i.e. the duplicate key was UniqueCode and not the ID column
do nothing
)