MySql 不存在則插入,存在則更新或忽略

2021-09-05 12:00:05 字數 1352 閱讀 9863

前言

在插入資料時,可能需要忽略或替換掉重複的資料(依據某個字段),這時可以在應用層處理,也可以使用複雜的 sql 語句來處理(如果僅僅知道一些簡單的 sql 語法的話),當然也可以使用一些簡單的 sql 語法,不過它並不是通用所有的資料庫型別。

以下所有例項僅針對mysql而言,並不能隨意用於其它資料庫

例項表名稱:student

表字段:

column name    primary key    auto increment    unique

id    true    true    

name            true

age            

初始表資料:

id    name    age

1    jack    18

注:以下所有的示例都需要被插入的資料中需要存在unique索引或primary key欄位,同時這裡引入表的主鍵id,並設定成自動遞增,後面可以看到它的變化

1. 不存在則插入,存在則更新

1.1 on duplicate key update

如果插入的資料會導致unique 索引或primary key發生衝突/重複,則執行update語句,例:

-- 2 row(s) affected12

345這裡受影響的行數是2,因為資料庫中存在name='jack'的資料,如果不存在此條資料,則受影響的行數為1

最新的表資料如下:

id    name    age

1    jack    19

1.2 replace into

如果插入的資料會導致unique 索引或primary key發生衝突/重複,則先刪除舊資料再插入最新的資料,例:

replace into `student`(`name`, `age`) values('jack', 18);

-- 2 row(s) affected12

3這裡受影響的行數是2,因為資料庫中存在name='jack'的資料,並且id的值會變成2,因為它是先刪除舊資料,然後再插入資料,最新的表資料如下:

id    name    age

2    jack    19

2. 避免重複插入

關鍵字/句:insert ignore into,如果插入的資料會導致unique索引或primary key發生衝突/重複,則忽略此次操作/不插入資料,例:

insert ignore into `student`(`name`, `age`) values('jack', 18);

-- 0 row(s) affected12

3這裡已經存在name='jack'的資料,所以會忽略掉新插入的資料,受影響行數為0,表資料不變。

MySQL記錄存在則更新,不存在則插入

create table tb file authorize authorize id int 11 not null auto increment,str id int 11 default null comment 使用者標識 file id int 11 default null commen...

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...

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

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