Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment a column if a row already exists with the same values

Tags:

sql

mysql

This one's a bit too tricky for my SQL-foo.

What I need to do is insert a new row (which contains 3 columns), unless a row already exists where two of those values are the same, and if it does exist, I need to increment the third value on that row.

Imagine the two values being a relationship (a, b) and the third value being the relationships's strength (which increases with every ocurrence of that relationship).

Thanks in advance!

like image 927
Filipe Avatar asked Mar 28 '11 15:03

Filipe


1 Answers

INSERT
INTO    a_b (a, b, strength)
VALUES  ($a, $b, 1)
ON DUPLICATE KEY
UPDATE  strength = strength + 1

Make sure you have a UNIQUE (a, b) or PRIMARY KEY (a, b) constraint on the table

like image 79
Quassnoi Avatar answered Oct 25 '22 12:10

Quassnoi