If on duplicate key update is specified at the end of the INSERT statement, and DUPLICATE values appear in a UNIQUE index or primary key after the row is inserted, the old row UPDATE is executed; if the unique value column is not duplicate, a new row is inserted. For example, if column a is defined as UNIQUE and contains a value of 1, the following two statements have the same effect:
1 2 3 4 |
Insert into table (a, B, c) VALUES (1, 2, 3) on duplicate key update c = c + 1;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.
For more information about the insert into... on duplicate key function, see MySQL reference documentation: 13.2.4. INSERT syntax.
Now the question is, how can I specify the value of the field after ON DUPLICATE KEY UPDATE if multiple rows are inserted? You must know that only one on duplicate key update exists in an INSERT statement. It will UPDATE a row of records or all rows to be updated. This problem has plagued me for a long time. In fact, all problems are solved by using the VALUES () function.
For example, field a is defined as UNIQUE, and records (, 9) and (, 1) exist in the table of the original database ), if the value of the inserted record is the same as the original record, the original record is updated; otherwise, a new row is inserted:
1 2 3 4 5 6 |
Insert into table (a, B, c) VALUES (1, 2, 3 ), (2, 5, 7 ), (3, 3, 6 ), (4, 8, 2) On duplicate key update B = VALUES (B ); |
When the preceding SQL statement is executed, if a in (, 7) conflicts with the unique value of the original record (, 9), The ON DUPLICATE KEY UPDATE statement is executed to UPDATE the original record, 9) Update (, 9), update (, 1) to (, 3, 1), insert new records (, 3), and (, 2)
Note: on duplicate key update is only a special MySQL syntax, not a standard SQL syntax!