Three commonly used statements to insert data in MySQL:
Insert into represents the insertion of data, the database checks the primary key, if there is a repeat error;
Replace into represents the insertion of replacement data, a PrimaryKey in the demand table, or a unique index that replaces the new data if the database already exists, if there is no data effect, and insert into;
Insert Ignore indicates that if the same record already exists in, the current new data is ignored;
The following are the differences between code descriptions, as follows:
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);
The SELECT * from testtb;//is still 1, "BB", 13, because the ID is the primary key, the primary key is duplicated but the error is ignored when the ignore is used
Replace into TESTTB (id,name,age) VALUES (1, "AA", 12);
SELECT * from TESTTB; Data into 1, "AA", 12
Give an example to explain
INSERT INTO
Table 1
ID Name
1 TB
2 ZP
Table2
ID (primary key) name
1 TB
2 CW
3 ZP
Insert Ignore into table1 select * from table2 execution result is
Table1
ID Name
1 TB
2 ZP
3 ZP
Note: If you use INSERT into find duplicate error, and insert ignore into found that the row of data to be inserted contains a unique index of the field value already exists, will discard this row of data, do not do any processing
Replace into
Table 1
ID name PS
1 TB A
2 ZP b
Table2
ID (primary key) name
1 TB
2 CW
3 ZP
Replace into table1 select * Table2 execution result is
Table1
ID name PS
1 TB NULL
2 CW NULL
3 ZP NULL
Note: Replace found repeated first delete and then insert, if the record has more than one field, if the insertion of a field when there is no assignment, then the newly inserted records these fields are blank.
Summarize
The difference between nsert IGNORE and insert is that insert IGNORE ignores data that already exists in the database, inserts new data if the database has no data, and skips the data if it has data. This preserves the data that already exists in the database for the purpose of inserting data in the gap.