📜  mysql on duplicate key update get value from values - SQL (1)

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

MySQL on Duplicate Key Update Get Value from Values

MySQL's ON DUPLICATE KEY UPDATE statement is a powerful tool for updating existing rows or inserting new ones if a duplicate key is found. However, sometimes you may want to update a value in the new row using a value from the existing row. This can be accomplished using the VALUES() function in combination with the ON DUPLICATE KEY UPDATE statement.

Syntax

The syntax for using ON DUPLICATE KEY UPDATE with VALUES() function is as follows:

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

In the ON DUPLICATE KEY UPDATE clause, we specify the columns to be updated by setting their values to VALUES(column_name). The VALUES() function retrieves the value from the same column in the row being inserted.

Example

Let's assume we have a table named employees with the following structure:

CREATE TABLE employees (
  id INT PRIMARY KEY, 
  name VARCHAR(50), 
  salary INT
);

Suppose we want to insert a new employee record with an ID of 100 and a name of 'John' and a salary of 5000. If the ID already exists, we want to update the employee's salary with the new value. We can accomplish this using ON DUPLICATE KEY UPDATE as follows:

INSERT INTO employees(id, name, salary) 
VALUES (100, 'John', 5000) 
ON DUPLICATE KEY UPDATE salary = VALUES(salary);

In this example, if a row with an ID of 100 already exists in the employees table, the salary column will be updated to 5000, otherwise a new row will be inserted into the table with the specified values.

Conclusion

In conclusion, ON DUPLICATE KEY UPDATE with VALUES() function allows us to update a value in the new row using a value from the existing row. This can be very useful in certain scenarios and can save a lot of time and effort when dealing with duplicate key conflicts.