在数据存储过程中,可能会遇到数据主键重复的情况,我们可以通过下面几个方法进行处理:若数据不存在插入,存在更新
使用duplicate key关键字,如插入数据时发生主键冲突就更新数据
使用Ingore关键字
使用replace into关键字
一、若数据不存在插入,存在更新:
sql = "select name from table where name = ?";
if:
sql = "update table set name = 'lqp'";
else:
sql = "INSERT INTO mt_brand(id,name,initial,url,update_time)";
二、使用duplicate key关键字,如插入数据时发生主键冲突就更新数据
如果数据表存在主键或者索引,可以使用 on duplicate key 来实现重复数据更新insert into 表名(zhihu_id, topics, url, title, content, answer_num, comments_num,
watch_user_num, click_num, crawl_time
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE content=VALUES(content), answer_num=VALUES(answer_num), comments_num=VALUES(comments_num),
watch_user_num=VALUES(watch_user_num), click_num=VALUES(click_num)
三、使用Ingore关键字:
如果是用主键primary或者唯一索引unique区分了记录的唯一性,避免重复插入记录可以使用ingore关键字。
格式如:INSERT IGNORE INTO 或者 UPDATE IGNORE SET
eg: insert ingore into test(?,?) values(1,”test”);
四、使用replace into关键字:
replace into 是insert into的增强版。在向表中插入数据时,首先判断数据是否存在;如果不存在,则插入;如果存在,则更新。即旧记录与新记录有相同的值,则在新记录被插入之前,旧记录被删除。
逻辑类似于:if not exists (select 1 from t where id = 1) ?
insert into t(id, update_time) values(1, getdate())
else
update table set update_time = getdate() where id = 1
MySQL replace into 有三种形式:
1、 replace into table(col_name, …) values(…)
用法类似于insert into的方法
2、 replace into table(col_name, …) select …
eg:replace into table1( name, age,) select name, rage from table2;
3、 replace into table name=value, …
用法类似于update set用法,使用一个例如“SET name = name + 1”的赋值,则对位于右侧的列名称的引用会被作为DEFAULT(name)处理。因此,该赋值相当于SET name = DEFAULT(name) + 1。