如果密钥存在则如何更新,否则插入

时间:2020-07-09 00:58:12

标签: mysql sql database

假设为您提供了具有唯一用户ID的用户数据。如何在没有竞争条件的情况下实现原子事务。

-如果count> 0 UPDATE,请选择匹配的行,否则INSET 要么 -你会更新吗?如果有0行影响了INSERT

1 个答案:

答案 0 :(得分:0)

该操作称为“ upsert”。在MySQL中,通常使用insert . . . on duplicate key update

insert into t (cols . . .)
    values ( . . . )
    on duplicate key set col = ?, . . . ;