Common database batch insert, how not to insert duplicate data? Mysql 4 ways to avoid repeated data insertion!

The most common way is to set a primary key or a unique index for a field. When inserting duplicate data, an error is thrown and the program terminates, but this will cause trouble for subsequent processing, so special processing is required for the insert statement, and try to avoid or ignore it Abnormal, let me briefly introduce it, and interested friends can try it:

Here, for the convenience of demonstration, I created a new user test table, which mainly has four fields: id, username, sex, and address. The primary key is id (self-incrementing), and a unique index is set for the username field:

When inserting data, if there is an error, such as duplicate data, no error will be returned, only a warning will be returned. So use ignore to make sure that there is no problem with the statement itself, otherwise it will be ignored. For example:

INSERT IGNORE INTO user (field) VALUES ('xxx')

Note that ignore has other side effects, please check the specific meaning of ignore.

 

2、on duplicate key update

When the primary or unique is repeated, the update statement is executed. If the update is a useless statement, such as id=id, it has the same function as 1, but the error will not be ignored.

For example, in order to insert data with duplicate names without reporting an error, you can use the following statement:

INSERT INTO user (field) VALUES ('xxx') ON duplicate KEY UPDATE id = id

This method has a prerequisite, that is, the constraint that needs to be inserted needs to be a primary key or a unique constraint (in your business, if you want to use it as the only judgment, set that field as the unique constraint, that is, the unique key).

3、insert … select … where not exist

To judge whether to insert according to the condition of select, it can be judged not only by primary and unique, but also by other conditions. For example:

INSERT INTO user (field) SELECT 'xxx' FROM dual WHERE NOT EXISTS (SELECT id FROM user WHERE id = 1)

This method actually uses a temporary table in mysql, but subqueries are used in it, and the efficiency will be affected a little bit. If you can use the above, don't use this.

4、replace into

If there is a record with the same primary or unique, delete it first. Then insert a new record.

REPLACE INTO user SELECT 1, 'telami' FROM books

This method is to delete and then insert no matter whether there is the same record or not.

 

Guess you like

Origin blog.csdn.net/zlfjavahome/article/details/132208752