views:

118

answers:

2

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
)
+2  A: 

Something like this?

mysql> insert into Foo (Id, UniqueCode) values (3, "bar") on duplicate key update
UniqueCode=IF(UniqueCode='bar','bar','no_unique_dupe');
ggiroux
A: 

I think my desired behavior is to not have an error occur on the off chance that the unique code is a duplicate. I've since implemented a method to check to see if the unique code exists before inserting it into the database. After that, I insert the row, then ON DUPLICATE KEY UPDATE can only fire if the ID is a duplicate.

Secret Agent Man