MySQL bulk insert and update data already exists

There is a phenomenon often on business, you need to bulk insert data into multiple tables, but in the implementation process, probably because the only key to the conflict, which led to bulk insert failure.

Thus it requires prior determination of what data is repeated, which is new.

The more common approach is to find existing data, and the data area does not exist in its separate update a section of the existing data. Then there is no data batch updates.

This method leads to a complex code logic, while severely reducing the efficiency of the code.

In response to this business scenario, MySQL has a proprietary syntax (insert into ... on duplicate key update) bulk insert and update the unique key data

CREATE TABLE `user_card` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  `uid` int(10) DEFAULT '0' COMMENT '用户ID',
  `grade_id` int(10) DEFAULT '0' COMMENT '等级ID',
  `name` varchar(255) DEFAULT ''The COMMENT ' name ' , 
  ` Money ` decimal ( 10 , 2 ) the DEFAULT  ' 0.00 ' the COMMENT ' balance ' ,
   a PRIMARY  KEY ( `id`),
   UNIQUE  KEY ` uid_gid` (uid` `,` grade_id`)     - on business unique key 
) ENGINE = MyISAM the AUTO_INCREMENT = . 6  the DEFAULT the CHARSET = UTF8;

As shown above, bulk insert data recorded experience already exists (determination according UNIQUE KEY unique key, creating the table statement), the automatic update existing data.

If the table has a plurality of unique keys (which may be a separate index or composite index), any one of the unique key (UNIQUE KEY) conflicts, automatically update the data.

By on duplicate key update syntax, you can specify which fields to be updated, which fields are not updated.

All operations by SQL processing, no additional program code analysis, can significantly improve the efficiency of program execution.

Guess you like

Origin www.cnblogs.com/funsion/p/11432758.html