Performing an UPDATE or INSERT depending whether a row exists or not in MySQL

前端 未结 6 940
小鲜肉
小鲜肉 2020-12-06 14:30

In MySQL, I\'m trying to find an efficient way to perform an UPDATE if a row already exists in a table, or an INSERT if the row doesn\'t exist.

I\'ve found two possi

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 15:19

    REPLACE INTO would be a solution, it uses the UNIQUE INDEX for replacing or inserting something.

    REPLACE INTO
        yourTable
    SET
        column = value;
    

    Please be aware that this works differently from what you might expect, the REPLACE is quite literally. It first checks if there is a UNIQUE INDEX collision which would prevent an INSERT, it removes (DELETE) all rows which collide and then INSERTs the row you've given it.

    This, for example, leads to subtle problems like Triggers not firing (because they check for an update, which never occurs) or values reverted to the defaults (because you must specify all values).

提交回复
热议问题