开发者社区> 问答> 正文

python怎么去重复数据库

python怎么去重复数据库

展开
收起
云计算小粉 2018-05-10 20:10:54 2141 0
1 条回答
写回答
取消 提交回答
  • 阿里云用户

    在数据存储过程中,可能会遇到数据主键重复的情况,我们可以通过下面几个方法进行处理: 

    1. 若数据不存在插入,存在更新 
    2. 使用duplicate key关键字,如插入数据时发生主键冲突就更新数据 
    3. 使用Ingore关键字 
    4. 使用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。

    2019-07-17 22:23:30
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载