postgresql 實現自動去重新增資料
針對這個問題,我先建張表,依據這個表再說明解決方案
表:
create table customer_table
(
id serial not null,
customer_id varchar(32),
identity_idvarchar(32),
customer_namevarchar(128),
)
comment on table customer_table is '客戶資訊表';
comment on column id is '主鍵';
comment on column customer_id is '客戶id';
comment on column identity_id, is '客戶身份id';
comment on column customer_name is '客戶名稱';
create index idx_customer_table_customer_id on customer_table (customer_id);
create unique index uk_customer_table_customer_id_identity_id on customer_table (customer_id,identity_id);
解決方案一、
我們可以直接通過設定唯一約束欄位或唯一約束索引,基於這個唯一約束,做衝突判斷,然後做更新處理,實現案例如下:
自動去重新增sql:
insert into customer_table (customer_id,identity_id,customer_name)
(#{customerId,jdbcType=VARCHAR},#{identityId,jdbcType=VARCHAR},#{customerName,jdbcType=VARCHAR})
on conflict (customer_id,identity_id) do update
set customer_name=#{customerName,jdbcType=VARCHAR}
解決方案二、
有些時候我們不能使用 on conflict 進行衝突判斷,那麼就需要我們自己判斷衝突點了,案例如下
insert into customer_table (customer_id,identity_id,customer_name)
(select
#{customerId,jdbcType=VARCHAR},#{identityId,jdbcType=VARCHAR},#{customerName,jdbcType=VARCHAR}
where not exists (
select id fromcustomer_table
wherecustomer_id =#{customerId,jdbcType=VARCHAR}
andidentity_id =#{identityId,jdbcType=VARCHAR}
)
)
總結:
方案二呢,使用更靈活,不依賴於唯一性約束欄位的建立,但是不好做更新,所以兩種方案各有利弊,可以現實場景自由選擇