MySQL防止重複插入相同記錄

2022-09-18 05:24:42 字數 1249 閱讀 9532

我們在用insert往資料表中插入資料時,為了不重複插入資料,往往先在資料表中查詢一下該條資料是否已經存在,若不存在才進行插入。

這樣比較麻煩。

找到乙個方法:使用 insert if not exists語句,就不需做上述兩道工序,輕鬆防止插入重複資料。

語法:

insert into table (field1, field2, fieldn) select

'field1',

'field2',

'fieldn'

from

dual

where

not exists (

select

field

from

table

where

field = ?

)

舉例:(user_form表userid為主鍵,username欄位不希望插入重複資料)

insert into user_inform (userid, username,name) select

5,'ad1',

'小張'from

dual

where

not exists (

select

username

from

user_inform

where username = 'ad1')

第一次執行時,執行結果:

受影響的行: 1

插入成功。

再次執行,執行結果:

受影響的行: 0

達到效果,並未插入重複資料。

如果希望username和name兩個字段不能同時重複,則修改為如下**(修改了括號中的最後乙個where語句),

insert into user_inform (userid, username,name) select

5, 'ad1',

'小張'

from

dual

where

not exists (

select

username

from

user_inform

where username = 'ad1' and name = '小張'

)

另外,還可通過使用mysql的索引,同時使用「insert ignore into」語句,這個方法也可以避免插入重複資料,可參考此篇文章:

參考部落格:

mysql 防止重複插入資料

mysql 防止重複插入資料 一 利用on duplicate key update語句 insert into mac netbar values ff 001001001000000 on duplicate key update mac addr ff netbar id 0010010010...

Mysql避免重複插入記錄

可使用ignore關鍵字 如果有用主鍵primary key或者唯一索引unique區分了記錄的唯一性,當我們無意插入相同資料的時候 主鍵值或是唯一索引值重複 insert into table name email,phone,user id values test 163.com 99999 9...

mysql避免重複插入記錄

1.ignore,如果遇到新插入的資料中與原有資料有唯一鍵衝突,會忽略操作,返回0 insert ignore into table name email phone user id values test9 163.com 99999 9999 2.replace,如果有衝突,會進行兩個操作 刪除...