Mysql 批量操作,存在更新,不存在插入

2021-10-12 02:35:24 字數 2403 閱讀 4106

在大量資料插入,但是有很多重複資料。假設有如下資料**

語法如下

insert into `table_name` (clo1,col2,...) 

values

(val1-1,val1-2,...),

(val2-1,val2-2,...),

(val3-1,val3-2,...),

on duplicate key update

clo1= values(clo1),

clo2= values(clo2);

首先,我們需要定義乙個unique key來避免重複鍵

在 on duplicate key update(重複更新)的操作的時候,採用了values()方法來更新資料

案例

create table `bt_product_synchronize_index` (

`id` bigint(20) not null auto_increment comment '記錄編號',

`company_id` int(20) not null comment '企業編號',

`product_id` varchar(50) default '' comment '商品編號',

`code` varchar(255) not null comment '貨號',

`type` tinyint(4) not null comment '更新型別 1:商品 2:渠道商品',

`operate_type` tinyint(4) default null comment '操作方式 1:新增 2:修改 3:刪除',

`creater` varchar(100) not null comment '建立者',

`created` timestamp not null default '0000-00-00 00:00:00' comment '建立者',

`modifier` varchar(100) not null comment '修改者',

`modified` timestamp not null default '0000-00-00 00:00:00' on update current_timestamp comment '修改時間',

primary key (`id`),

unique key `idx_company_code_type` (`company_id`,`code`,`type`) using btree

) engine=innodb auto_increment=2712 default charset=utf8 comment='商品同步索引對列表';

注意,唯一鍵

unique key `idx_company_code_type` (`company_id`,`code`,`type`) using btree
我們需要批量插入資料,但是如果有的話,那麼就更新modified + modifier,現有資料如下:

執行如下指令碼:

insert into `bt_product_synchronize_index`(`company_id`, `product_id`, `code`, `type`, `operate_type`,

`creater`, `created`, `modifier`, `modified`)

values

(10124, 'pid-00101','1012412145873543323035', 1, 1, '', now(), 'updater1', now()),

(10124, 'pid-00101','1012412145873543323035', 1, 1, '', now(), 'updater2', now()),

(10124, 'pid-008', 'code-008',1, 1,'inserter', now(), 'inserter', now())

on duplicate key update

modifier = values(modifier),

product_id = values(product_id),

modified = values(modified),

operate_type = values(operate_type);

期待結果:

第一條資料被忽略

第二條資料更新第一條資料,modifier + modified

第三天資料執行insert 注意

如果需要判斷是否為空,用ifnull(),判斷傳入是否和預設值相同,用default()函式

mysql存在更新不存在新增

1 插入一條資料,存在則不操作,不存在就插入 必須現有唯一鍵 使用insert ignore語句 insert ignore into table col1,col2 values a b 例如插入資料 insert ignore into user info last name,first nam...

不存在 MySQL資料存在就更新,不存在就新增

做業務系統,經常遇到初始化一些資料,但如果每次都檢查就比較麻煩,下面的方法可以解決類似的問題。使用on duplicate插入的字段中必須有唯一約束,否則會出現重複值 目前表中沒有唯一約束,執行兩遍插入語句,會出現兩個重複資料,id為49的jerry和id為50的jerry,並沒有達到修改的目的,將...

mysql,存在就更新,不存在就插入

mysql 當記錄不存在時插入,當記錄存在時更新 網上基本有三種解決方法。第一種 示例一 插入多條記錄 假設有乙個主鍵為 client id 的 clients 表,可以使用下面的語句 insert into clients client id,client name,client type sel...