Copy codeThe Code is as follows:
INSERT table (auto_id, auto_name) values (1, 'yourname') on duplicate key update auto_name = 'yourname'
ON DUPLICATE KEY UPDATE
If you specify on duplicate key update and insert a row, DUPLICATE values will appear in a UNIQUE index or primary key, the old row will be updated. For example, if column a is defined as UNIQUE and contains a value of 1, the following two statements have the same effect:
Copy codeThe Code is as follows:
Mysql> insert into table (a, B, c) VALUES (1, 2, 3)
-> On duplicate key update c = c + 1;
Mysql> UPDATE table SET c = c + 1 WHERE a = 1;
If a row is inserted as a new record, the value of the affected row is 1. If the original record is updated, the value of the affected row is 2.
NOTE: If Column B is also a unique column, INSERT is equivalent to this UPDATE statement:
Copy codeThe Code is as follows:
Mysql> UPDATE table SET c = c + 1 WHERE a = 1 OR B = 2 LIMIT 1;
If a = 1 OR B = 2 matches multiple rows, only one row is updated. Generally, you should avoid using the on duplicate key clause for tables with multiple unique keywords.
You can use the VALUES (col_name) function in the UPDATE clause to reference the column VALUES from the INSERT section of the INSERT... UPDATE statement. In other words, if there is no duplicate keyword conflict, the VALUES (col_name) in the UPDATE clause can reference the value of the inserted col_name. This function is particularly applicable to multiline inserts. The VALUES () function only makes sense in the INSERT... UPDATE statement. Otherwise, NULL is returned.
Example:
Copy codeThe Code is as follows:
Mysql> insert into table (a, B, c) VALUES (1, 2, 3), (4, 5, 6)
-> On duplicate key update c = VALUES (a) + VALUES (B );
This statement serves the same purpose as the following two statements:
Copy codeThe Code is as follows:
Mysql> insert into table (a, B, c) VALUES (1, 2, 3)
-> On duplicate key update c = 3;
Mysql> insert into table (a, B, c) VALUES (4, 5, 6)
-> On duplicate key update c = 9;
When you use on duplicate key update, the DELAYED option is ignored.