Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ON DUPLICATE KEY UPDATE for Specific Key in Multi-Key Table

Tags:

mysql

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
)
like image 759
Doctor Blue Avatar asked Dec 30 '25 00:12

Doctor Blue


1 Answers

Something like this?

mysql> insert into Foo (Id, UniqueCode) values (3, "bar") on duplicate key update
UniqueCode=IF(UniqueCode='bar','bar','no_unique_dupe');
like image 197
ggiroux Avatar answered Jan 01 '26 13:01

ggiroux