MySQL 避免重複插入時如何寫SQL

2021-09-17 07:24:15 字數 796 閱讀 4260

假設紅色部分為我在**中需要插入的部分。

說明:下面的sql語句示例是我用於python中的**片段,所以使用了%s的寫法,如果直接寫sql或想要在其他語言中使用只需稍作修改。

insert ignore into chi_variant_words_lib (original_word, variant_word, is_need_validated, createtime) values (%s,%s,%s, now())
注意:使用該方法有前提條件,即插入的記錄必須有用主鍵primary或者唯一索引unique區分了記錄的唯一性的字段。

insert into chi_variant_words_lib (original_word, variant_word, is_need_validated, createtime) select %s, %s, %s, now() from dual where not exists (select * from chi_variant_words_lib where original_word=%s and variant_word=%s)
注意:這裡插入時可以不光是通過primary 和unique來判斷,也可通過其它非唯一性字段進行是否需要插入的判斷。這種方法更通用,也比較符合我上面的插入需求,所以我最後在**中採用的此方法。

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,如果有衝突,會進行兩個操作 刪除...

MySQL 避免重複插入 IGNORE

mysql 提供了ignore 用來避免資料的重複插入.ignore 若有導致unique key 衝突的記錄,則該條記錄不會被插入到資料庫中.示例 insert ignore into table name email phone user id values test qq.com 123 11...