What is the difference between insert into, replace into, and insert ignore in MYSQL? mysqlignore
The following statements are commonly used in mysql to insert data:
Insert into indicates that the data is inserted. The database checks the primary key (PrimaryKey). If there is a duplicate, an error is returned;
Replace into indicates insertion and replacement of data. If the table requires a PrimaryKey or unique index, if the database already has data, replace it with new data. If there is no data effect, it is the same as insert;
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.
Insert ignore indicates that if the same record already exists, the current new data is ignored;
Note: These are all based on the primary key...
The following code describes the differences between them:
Create table testtb (
Id int not null primary key,
Name varchar (50 ),
Age int
);
Insert into testtb (id, name, age) values (1, "bb", 13 );
Select * from testtb;
Insert ignore into testtb (id, name, age) values (1, "aa", 13 );
Select * from testtb; // It is still 1, "bb", 13. Because id is the primary key, the primary key is repeated, but ignore is used, the error is ignored.
Replace into testtb (id, name, age) values (1, "aa", 12 );
Select * from testtb; // The data is changed to 1, "aa", 12