mysql ON DUPLICATE KEY UPDATE 演示

2024-10-09 08:01:01 浏览数 (1)

<e>查询:INSERT INTO member_test(mem_no,flag)VALUE('111','1')

错误代码: 1062 Duplicate entry '111' for key 'uk_mem_no'

1.创建数据库表演示

代码语言:javascript复制
CREATE TABLE `member_test` (
  `id` INT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `mem_no` INT(11) NOT NULL,
  `flag` INT(2) NOT NULL DEFAULT '0' COMMENT '是否是测试会员,0不是,1是',
  `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_delete` TINYINT(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_mem_no` (`mem_no`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='会员测试信息';

2.在遇到主键冲突的时候,跳过不报错。不主键冲突则新增,否则修改(含本条记录不修改)

代码语言:javascript复制
#查询
SELECT * FROM member_test;
#初始化
INSERT INTO member_test(mem_no,flag)VALUE('111','1');
#错误代码: 1062 Duplicate entry '111' for key 'uk_mem_no'
INSERT INTO member_test(mem_no,flag)VALUE('111','1');


##有主键冲突修改  影响行数2
INSERT INTO member_test(mem_no,flag)VALUE('111','1')
ON DUPLICATE KEY UPDATE flag = flag - 1;

##无主键冲突新增  影响行数1
INSERT INTO member_test(mem_no,flag)VALUE('222','1')
ON DUPLICATE KEY UPDATE flag = flag;

##有主键冲突无修改 影响行数0
INSERT INTO member_test(mem_no,flag)VALUE('222','1')
ON DUPLICATE KEY UPDATE flag = flag;

0 人点赞