Usage of MySQL replace into
grammar:
- REPLACE [LOW_PRIORITY | DELAYED]
- [INTO] tbl_name
- [PARTITION (partition_name,...)]
- [(col_name,...)]
- {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
The functions of replace and insert are the same, both insert data. When inserting data with insert, if the primary key or unique index contained in the inserted record already exists, the insertion will fail.
E.g:
With replace, if this happens, the existing record will be deleted first, and then the new record will be inserted
E.g:
You can see that the affected rows are 2, and the affected rows of the replacement = the number of rows deleted + the number of newly inserted rows
To achieve the effect of updating if it already exists, you can also use the syntax of insert into ... on duplicate key update ..., for example
The parameter of the values function is the column name, and returns the value of the column corresponding to the currently inserted row
It can be seen that if the primary key already exists, the insertion will not be performed, but the logic behind the update will be executed