One of the most common way is to set the primary key or unique index for field, when inserted into the duplicate data, throw an error, the program is terminated, this can cause trouble for subsequent processing, so need to make special treatment in the insert statement, as far as possible to avoid or ignore abnormal, let me make a brief introduction, interested friends can try:

Select * from user where id, username, sex, address is the primary key; select * from user where id is the primary key; select * from user where id is the primary key;

1, insert ignore into

Namely when inserting data, if the data exist, it ignores the inserts, premise condition is inserted into the data fields set the primary key or unique index, test the SQL statement as follows, when inserting data, this article will first retrieve the MySQL database for data (i.e., idx_username index), if present, is to ignore the insert, if not, Data is normally inserted:

2. On Duplicate key Update

MySQL > insert (idx_USERNAME); MySQL > insert (idx_USERNAME); MySQL > insert (idx_USERNAME); Update; if not, insert:

3, the replace into

Is inserted into the data, if the data is deleted to insert again, premise condition as above, insert data fields need to set up the primary key or unique index, test the SQL statement as follows, when insert the record of this article, the MySQL database will first retrieve the existing data (idx_username index), if there is, first remove the old data, then to insert again, If not, insert directly:

4、 insert if not exists

The insert into… The select… where not exist … When inserting a data, check whether the data exists in the MySQL database first. If not, insert the data normally. If yes, ignore it:

Now, just to share this four MySQL processing mode of the duplicate data, the former three methods suitable for field set the primary key or unique index, and finally a way there is no this limit, as long as you are familiar with the use process, will soon be able to master, Internet also has the relevant information and tutorials, very detailed introduction, are interested, you can search.