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?
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.
A unique constraint guarantees that no duplicate values can be inserted into the column(s) on which the constraint is created.
Columns with primary or unique keys cannot have duplicate values.
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.
make UNIQUE KEY
to (a,b)
not to b
ALTER TABLE tblname ADD UNIQUE (a,b)
CREATE UNIQUE INDEX index_unique_on_a_and_b ON mytable (a,b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With