Create if an entry doesn't exist, otherwise update?

后端 未结 4 1877
太阳男子
太阳男子 2021-01-30 14:07

Kinda strange to put it into words that short, heh.

Anyway, what I want is basically to update an entry in a table if it does exist, otherwise to create a new one fillin

4条回答
  •  情歌与酒
    2021-01-30 14:15

    Look up REPLACE in the MySQL manual.

    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”.

    REPLACE is a MySQL extension to the SQL standard. It either inserts, or deletes and inserts. For another MySQL extension to standard SQL — that either inserts or updates — see Section 12.2.5.3, “INSERT ... ON DUPLICATE KEY UPDATE Syntax”.

    If you have the following INSERT query:

    INSERT INTO table (id, field1, field2) VALUES (1, 23, 24)
    

    This is the REPLACE query you should run:

    REPLACE INTO table (id, field1, field2) VALUES (1, 23, 24)
    

提交回复
热议问题