SQL執行不存在則插入 Mysql,冪等

2021-08-28 09:13:32 字數 1911 閱讀 1556

一. sql的冪等

最近在執行軟體公升級過程中的資料庫sql的執行需要滿足冪等性,即無論這些sql執行了多少次,它們執行的結果是完全一致的。這裡先提示一下有三種方法,唯一索引;not exists;not in;

二. 冪等sql實現方法

①唯一索引

唯一索引的方法是利用了資料庫索引的特性,將不能重複的字段建立唯一索引,那麼當你在執行sql插入的記錄會查詢索引中這條記錄是否存在,如果存在這條記錄則該次不會被插入

# 假設first_name和second_name共同確定乙個人,你需要先建立first_name和second_name的唯一索引

alter

table

`test`

addunique

(`first_name`

,`second_name`

);

# ignore會忽略資料庫已存在該記錄的warning

insert

ignore

into

`test`

(first_name,second_name)

values

("aa"

,"bb"

);

②not exists

如果不存在該記錄,則插入該記錄,這種寫法最多一次插入一條記錄。以下兩張寫法等同:

insert

ignore

into

`test`

select

'aa'

,'cao'

where

notexists

(select

1from test where

`first_name`

='aa'

and`second_name`

='bb');

insert

ignore

into

`test`

select

'aa'

,'cao'

from dual where

notexists

(select

1from test where

`first_name`

='aa'

and`second_name`

='bb'

);

③not in

可插入多條記錄,大多數資料庫是支援except關鍵字的,可以求差集,mysql不支援這個關鍵字,但是我們可以使用not in代替

# 將first_name=bb的second_name與first_name=aa的second_name做差集

insert

ignore

into

`test`

(`first_name`

,`second_name`

)select

`first_name`

,`second_name`

from

`test`

where

`first_name`

='aa'

and`second_name`

notin

(select

`second_name`

from

`test`

where

`first_name`

='bb'

);

MyBatis 如果不存在則插入

依靠資料庫鎖是非常安全的方式,比方說,分布式定時任務,除了使用quartz不讓各個機器上同時跑乙個定時任務之外,最好在資料庫也加乙個保險。插入一條資料之前,判斷表中有沒有這條資料,如果沒有才插入,這樣就只會有一條資料插入成功。insert into inno index id,depart name...

sql 存在更新,不存在插入

1 語法 if exists select from users where name 張三 print 1 else print 02 建表語句 create table dbo users id int not null identity 1,1 name varchar 50 null var...

Oracle存在則更新,不存在則插入應用

更新同一張表的資料。需要注意下細節,因為可能涉及到using的資料集為null,所以要使用count 函式。merge into mn a using select count co from mn where mn.id 4 b on b.co 0 這裡使用了count和 注意下,想下為什麼!wh...