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

前端 未结 6 927
小鲜肉
小鲜肉 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
    2020-12-06 15:10

    There is another way - REPLACE.

    REPLACE INTO myTable (col1) VALUES (value1)
    

    REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 12.2.5, “INSERT Syntax”.

提交回复
热议问题