Mysql implements the same merge into function as Oracle

     Today, in project practice, there is a function that requires two data of the same table structure to be combined. The requirement is that the data can be matched and then be updated and inserted. The merge into grammar can be used in Oracle to achieve this function. A similar syntax can be implemented in mysql, namely:

insert into 表名(表字段,表字段,表字段,表字段) select a.字段名,a.字段名,a.字段名 from 表2 a on duplicate key update 表1.待更新字段=表2.字段...;

Example:

Create a new table test:

CREATE TABLE `test`  (
  `key1` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
  `key2` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `key3` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`key1`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

Create a new table test1:

CREATE TABLE `test1`  (
  `key1` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
  `key2` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `key3` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`key1`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

Note that the two tables must have at least one unique index that is the same

Then insert the data separately: test

test1:

Execute sql statement:

insert into test(key1,key2,key3) 
select a.key1,a.key2,a.key3 from test1 a
on duplicate key update key2 = a.key2,key3 = a.key3;

Execution result: data changes in the test table:

It can be seen that the data in the red box in the first row has been updated, and the data in the fifth row has been added.

Guess you like

Origin blog.csdn.net/u013804636/article/details/108538386