Parse the difference between ReplaceINTO and INSERTINTO in SQL statements bitsCN.com
REPLACE runs like INSERT. There is only one exception. If an old record in the table has the same value as a new record used for the primary key or a UNIQUE index, the old record is deleted before the new record is inserted.
Note: Unless the table has a primary key or UNIQUE index, using a REPLACE statement is meaningless. This statement is the same as INSERT, because no index is used to determine whether other rows have been copied in the new row.
The values of all columns are equal to the value specified in the REPLACE statement. All missing columns are set as their default values, which is the same as INSERT. You cannot reference a value from the current row or use a value in a new row. If you use a value such as "SET col_name = col_name + 1", the reference to the column name on the right will be processed as DEFAULT (col_name. Therefore, the value is equivalent to SET col_name = DEFAULT (col_name) + 1.
To use REPLACE, you must have both the INSERT and DELETE permissions for the table.
The REPLACE statement returns a number to indicate the number of affected rows. This is the sum of the number of deleted and inserted rows. If this number is 1 for a single row, one row is inserted and no row is deleted. If the number is greater than 1, one or more old rows are deleted before the new row is inserted. If the table contains multiple unique indexes, and the new row copies the values of different old rows in different unique indexes, it is possible that a single row replaces multiple old rows.
The number of affected rows can be easily determined whether REPLACE only adds one row, or whether REPLACE also replaces other rows: Check whether the number is 1 (added) or larger (replaced ).
If you are using c api, you can use the mysql_affected_rows () function to obtain the number of affected rows.
Currently, you cannot change a table in a subquery and select from the same table.
Detailed description of the algorithm below (this algorithm is also used to load data... REPLACE ):
1. try to insert a new row into the table
2. when insertion fails due to a duplicate keyword error for the primary key or unique keyword:
A. delete conflicting rows with duplicate keyword values from the table
B. try to insert a new row into the table again
The format is as follows:
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name [(col_name,...)]
VALUES ({expr | DEFAULT },...), (...),...
Or:
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name
SET col_name = {expr | DEFAULT },...
Or:
REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name [(col_name,...)]
SELECT...
BitsCN.com