INSERT a new if it doesn't exist, and UPDATE if it does

…衆ロ難τιáo~ 提交于 2020-01-15 09:46:05

问题


I need to insert a new record on BD if it doesn't exist, and update if it does. For this, I use 2 queries:

INSERT  INTO tbl_ponto ( `rodada`, `ponto`, `patrimonio`, `FK_loginID` ) VALUES ( '10', 100.00, 100.00, 3 );
UPDATE tbl_ponto SET ponto=150.00, patrimonio=150.00 WHERE rodada=10 AND FK_loginID=3;

I would do this with just 1 query. I read about REPLACE but could not make it work in my case. Could you please help me?


回答1:


INSERT INTO tbl_ponto (`rodada`, `ponto`, `patrimonio`, `FK_loginID`)
    VALUES ('10', 100.00, 100.00, 3)
ON DUPLICATE KEY UPDATE ponto=150.00, patrimonio=150.00;

The trigger ON DUPLICATE KEY is called when the INSERT fails because some of the values conflict with a PRIVATE/UNIQUE KEY that already exists.

In this case, rodada, FK_loginID must be PRIVATE KEY or UNIQUE KEY, otherwise you will have to update one of those values.



来源:https://stackoverflow.com/questions/24813578/insert-a-new-if-it-doesnt-exist-and-update-if-it-does

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!