Reputation: 4408
Let's say i have two
fields a
and b
.
Now let's say i want to write a query which would update if a = 100 AND b = 120
else it would create new field.
Also a
and b
have to be unique to each other, what i mean is that it can be two a
equals to 100
or two b
equals to 200
, but there can't be more fields like
a
= 100
and b
= 120
, i hope you get what i mean.
Upvotes: 1
Views: 381
Reputation: 115510
If you have a UNIQUE
constraint on the (a,b)
combination, you can use the INSERT ... ON DUPLICATE KEY UPDATE ...
syntax for this functionality. Examples:
INSERT INTO TableX
( a, b, c, d, e)
VALUES
( 100, 200, 1, 2, 3)
ON DUPLICATE KEY UPDATE
c = VALUES(c)
, d = VALUES(d)
, e = VALUES(e)
INSERT INTO TableX
( a, b, c, d, e)
VALUES
( 100, 200, 1, 7, 20)
ON DUPLICATE KEY UPDATE
c = c + 1
, d = d + 1
, e = e + 1
Upvotes: 4