📜  MySQL UPSERT(1)

📅  最后修改于: 2023-12-03 15:33:02.141000             🧑  作者: Mango

MySQL UPSERT

MySQL UPSERT refers to a combination of INSERT and UPDATE statements in a single query. The term UPSERT is derived from the combination of the words "update" and "insert."

Syntax

The basic syntax of MySQL UPSERT is as follows:

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...)
ON DUPLICATE KEY UPDATE
column1 = value1, column2 = value2, column3 = value3, ...;

In this syntax, the INSERT INTO statement is used to insert data into the specified table. The column names and their corresponding values are specified using the column1, column2, column3, ... and value1, value2, value3, ... placeholders, respectively.

The ON DUPLICATE KEY UPDATE clause is then used to update the columns of the table in case the value being inserted conflicts with an existing record in the table.

It is important to note that the table should have a unique index or primary key so that the ON DUPLICATE KEY UPDATE clause can function properly.

Example

Suppose we have a simple table named users with a username column and a password column:

CREATE TABLE users (
    username VARCHAR(20) PRIMARY KEY,
    password VARCHAR(20) NOT NULL
);

Now, let's say we want to insert a new record into this table. If the specified username already exists in the table, we want to update its password column:

INSERT INTO users (username, password)
VALUES ('john', 'password1234')
ON DUPLICATE KEY UPDATE
password = 'newpassword';

If the specified username doesn't exist in the table, a new record is created with the specified username and password.

Conclusion

MySQL UPSERT is a convenient feature that allows us to perform both INSERT and UPDATE operations in a single query. This can simplify our code and make it more efficient.