当前位置:网站首页>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】
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; | |
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; | |
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`) | |
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 ).
边栏推荐
- Microsoft Remote Desktop 10.7.6正式版
- Modular import and export collation in JS
- Cocoapods creates private libraries and publishes them
- 【宋红康 MySQL数据库 】【高级篇】【07】MySQL的存储引擎
- Detailed explanation of subnet mask
- Xmind 2022思维导图激活版资源?
- Use multithreading to speed up your crawler
- 【Oracle 數據庫】奶媽式教程 day13 日期函數
- [common template problems in graph theory] four shortest path solutions and two minimum spanning tree solutions
- Layer drawing method
猜你喜欢
随机推荐
Asynchronous sending and receiving of message passing based concurrent programming (MPI)
Node red sends wechat official account message (template message)
Applet /vant UI to upload files
Layer drawing method
Microsoft Remote Desktop 10.7.6 official
[multi thread programming] thread scheduling strategy and priority
Cocoapods problem record
模电实验——实验一 晶体管共射极单管放大器
Oracle execution plan analysis
【图论常见模板题】4种最短路解法和2种最小生成树解法
The difference between get and post requests
White paper on Web page quality of Baidu search engine guides website construction and optimization
MySQL transactions
Qualcomm platform LCM summary
Realization of readable and writable files in library management system with C language bidirectional linked list
Expérience électrique en mode - - expérience 2 circuit d'amplification de source commune JFET
【圖論常見模板題】4種最短路解法和2種最小生成樹解法
Difference between ID instancetype nsobject *
Daily maintenance of website
FileTool








