Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ON DUPLICATE KEY: multi-column unique constraint

Tags:

database

mysql

Right now I have:

INSERT INTO mytable (a,b,c,d) VALUES(1,2,3,4)
  ON DUPLICATE KEY UPDATE c=VALUES(c),d=VALUES(d)

which works if a or b are UNIQUE keys...

But now I want to UPDATE only when another row with the pair (a,b) doesn't exist in the table (otherwise skip insertion).

Basically (a,b) shoud be UNIQUE, not (a) or (b), but both connected.

For example these rows would be valid

ID (auto-inc) | a | b |  c  | d
            0 | 5 | 1 | 343 |466
            1 | 5 | 2 | 363 |466
            2 | 5 | 3 | 343 |496
            3 | 7 | 1 | 343 |496

Because there's 5,1, 5,2, 5.3, 7.1 etc.

But row #2 here should be considered duplicate of row #1, so row #1 should be updated:

ID (auto-inc) | a | b |  c  | d
            0 | 5 | 1 | 343 |466
            1 | 5 | 1 | 363 |466
            2 | 5 | 3 | 343 |496
            3 | 7 | 1 | 343 |496

Is this possible?

like image 731
Emma Avatar asked Jul 31 '11 12:07

Emma


People also ask

Can unique key created on multiple columns?

UNIQUE key does not allow duplicate values. UNIQUE key allows NULL values but does not allow NULL values multiple times. We can create multiple UNIQUE columns on one table however only one PRIMARY KEY for table. Defining primary key on a column has a UNIQUE constraint property by default.

Does unique constraint allow duplicate values?

A unique constraint guarantees that no duplicate values can be inserted into the column(s) on which the constraint is created.

Can unique key have duplicates?

Columns with primary or unique keys cannot have duplicate values.

Can we have multiple unique keys in SQL?

Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.


2 Answers

make UNIQUE KEY to (a,b) not to b

ALTER TABLE tblname ADD UNIQUE (a,b)
like image 74
RiaD Avatar answered Sep 28 '22 09:09

RiaD


CREATE UNIQUE INDEX index_unique_on_a_and_b ON mytable (a,b)
like image 25
M. Cypher Avatar answered Sep 28 '22 08:09

M. Cypher