开发者

MySQl: triggering an insertion before updating, if the not existing

开发者 https://www.devze.com 2023-04-05 06:56 出处:网络
I\'m 开发者_如何学Gonot really familiar with MySQL. But for performance reasons i want to avoid checking if a row already exists. Currently I\'ve got a table with 2 columns (num, count) and I do somet

I'm 开发者_如何学Gonot really familiar with MySQL. But for performance reasons i want to avoid checking if a row already exists. Currently I've got a table with 2 columns (num, count) and I do something like this:

SELECT num FROM numbers WHERE num = 123

then if row exists...

UPDATE numbers SET count = count + 456 WHERE num = 123

else if row not exists...

INSERT INTO numbers (num, count) VALUES (123, 456)

Is there a possibility to avoid always querying the table. Something like a trigger... In the end, i just want to make an UPDATE, so that insertion is done automatically. thanks in advance


You don't need to use triggers, all you have to do is add UNIQUE constraint to your num column and then:

INSERT INTO numbers SET num = 123, count = 456 ON DUPLICATE KEY UPDATE count = count + 1;

Also, don't use reserved words for column names such as COUNT.

0

精彩评论

暂无评论...
验证码 换一张
取 消