当前位置:网站首页>MySQL avoids the method of repeatedly inserting records (ignore, replace, on duplicate key update)

MySQL avoids the method of repeatedly inserting records (ignore, replace, on duplicate key update)

2022-06-22 08:00:00 xiaoke815

This article is to provide you with three ways in mysql To avoid repeated insertion of records in , It's mainly about ignore,Replace,ON DUPLICATE KEY UPDATE Three methods , You may try to refer to .

Case 1 : Use ignore keyword

If you use the primary key primary Or a unique index unique Distinguishing the uniqueness of records , To avoid repeated insertion of records, you can use :

  The code is as follows Copy code
1 INSERT IGNORE INTO `table_name` (`email`, `phone`, `user_id`) VALUES ('[email protected]', '99999', '9999');

In this way, when there are duplicate records, we will ignore , Return the number after execution 0

Another application is copying tables , Avoid duplicate records :

  The code is as follows Copy code
1 INSERT IGNORE INTO `table_1` (`name`) SELECT `name` FROM `table_2`;

Option two : Use Replace

Grammar format :

  The code is as follows Copy code
REPLACE INTO `table_name`(`col_name`, ...) VALUES (...);
REPLACE INTO `table_name` (`col_name`, ...) SELECT ...;
REPLACE INTO `table_name` SET `col_name`='value',

... Algorithm explain :
REPLACE The operation of and INSERT Very much alike , But if the old record has the same value as the new record , Before a new record is inserted , Old records are deleted , namely :

Try inserting new rows into the table  
When the insert fails due to a duplicate keyword error for the primary key or unique key : 
Key contains duplicate values from the table  
Try inserting the new row into the table again  
The criterion for judging whether an old record has the same value as a new record is :
There is one in the watch PRIMARY KEY or UNIQUE Indexes , otherwise , Use one REPLACE The sentence has no meaning . The sentence will be associated with INSERT identical , Because no index is used to determine whether new rows replicate other rows .

Return value :
REPLACE Statement will return a number , To indicate the number of rows affected . This number is the sum of the number of rows deleted and inserted
The number of rows affected can easily determine whether REPLACE Only one line has been added , Or Yes No REPLACE It also replaced other lines : Check if the number is 1( add to ) Or bigger ( Replace ).

Example :
# eg:(phone Fields are unique indexes )

  The code is as follows Copy code

REPLACE INTO `table_name` (`email`, `phone`, `user_id`) VALUES ('test569', '99999', '123');

in addition , stay SQL Server It can be done in this way :

  The code is as follows Copy code

if not exists (select phone from t where phone= '1')   insert into t(phone, update_time) values('1', getdate()) else    update t set update_time = getdate() where phone= '1'

For more information, see :http://dev.MySQL.com/doc/refman/5.1/zh/sql-syntax.html#replace

Option three :ON DUPLICATE KEY UPDATE

Such as ‍ It's written on , You can also be in INSERT INTO….. Followed by ON DUPLICATE KEY UPDATE Method to implement . If you specify ON DUPLICATE KEY UPDATE, And inserting a row will result in a UNIQUE Index or PRIMARY KEY Duplicate value in , Then follow the old line UPDATE.

for example , If the column a Is defined as UNIQUE, And contains the value 1, The following two statements have the same effect :

  The code is as follows Copy code

INSERT INTO `table` (`a`, `b`, `c`) VALUES (1, 2, 3) ON DUPLICATE KEY UPDATE `c`=`c`+1; 
UPDATE `table` SET `c`=`c`+1 WHERE `a`=1;

If the row is inserted as a new record , Then the value of the affected row is 1; If the original record is updated , Then the value of the affected row is 2.

notes : If the column b And the only column , be INSERT With this UPDATE Statement equivalent :

  The code is as follows Copy code

UPDATE `table` SET `c`=`c`+1 WHERE `a`=1 OR `b`=2 LIMIT 1;

If a=1 OR b=2 Match multiple row directions , Only one row is updated . Usually , You should try to avoid using ON DUPLICATE KEY Clause .

You can go to UPDATE Used in clauses VALUES(col_name) Function from INSERT…UPDATE Of the statement INSERT Partial reference column values . let me put it another way , If there is no duplicate keyword conflict , be UPDATE In Clause VALUES(col_name) You can refer to the inserted col_name Value . This function is especially suitable for multi line insertion .VALUES() Function is only in INSERT…UPDATE There is meaning in the sentence , It will return at other times NULL.

  The code is as follows Copy code

INSERT INTO `table` (`a`, `b`, `c`) VALUES (1, 2, 3), (4, 5, 6) ON DUPLICATE KEY UPDATE `c`=VALUES(`a`)+VALUES(`b`);

This statement has the same function as the following two statements :

  The code is as follows Copy code

INSERT INTO `table` (`a`, `b`, `c`) VALUES (1, 2, 3) ON DUPLICATE KEY UPDATE `c`=3; 
INSERT INTO `table` (`a`, `b`, `c`) VALUES (4, 5, 6) ON DUPLICATE KEY UPDATE c=9;

notes : When you use ON DUPLICATE KEY UPDATE when ,DELAYED Option ignored .

Example :
This is an example that I used in actual projects : Import data into another table , The repeatability of data has to be considered ( as follows ), The only index is :email:

  The code is as follows Copy code

INSERT INTO `table_name1` (`title`, `first_name`, `last_name`, `email`, `phone`, `user_id`, `role_id`, `status`, `campaign_id`) 
    SELECT '', '', '', `table_name2`.`email`, `table_name2`.`phone`, NULL, NULL, 'pending', 29 FROM `table_name2` 
    WHERE `table_name2`.`status` = 1 
ON DUPLICATE KEY UPDATE `table_name1`.`status`='pending'

Here's another example :

  The code is as follows Copy code

1 INSERT INTO `class` SELECT * FROM `class1` ON DUPLICATE KEY UPDATE `class`.`course`=`class1`.`course`

Other key :DELAYED  For quick insertion , I don't really care about failure , Improve insertion performance . 
IGNORE  Only focusing on the primary key does not exist , If nothing, add , If there is one, ignore .

For more information, see :  http://dev.mysql.com/doc/refman/5.1/zh/sql-syntax.html#insert

In particular : stay MYSQL in UNIQUE The index will null Field invalid , in other words (a Create a unique index on the field ):

  The code is as follows Copy code

1 INSERT INTO `test` (`a`) VALUES (NULL);

It can be inserted repeatedly ( The same goes for federated unique indexes ).

原网站

版权声明
本文为[xiaoke815]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202220530339688.html