zoukankan      html  css  js  c++  java
  • 使用pymysql循环删除重复数据,并修改自增字段偏移值

    创建表:

      CREATE TABLE `info` (
      `id` tinyint NOT NULL AUTO_INCREMENT,
      `name` varchar(20) NOT NULL,
      PRIMARY KEY (`id`)
      ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 

    插入数据:INSERT INTO info(`name`) VALUE('张三'),('李四'),('麻婆'),('王五');

    再插入一次:INSERT INTO info(`name`) VALUE('张三'),('李四'),('麻婆'),('王五');

    再插入一次:INSERT INTO info(`name`) VALUE('张三'),('李四'),('麻婆'),('王五');

    看见好多重复数据了吧,干掉它!

    delete from info where info.id in 
    (select tmp.id from
    (select max(id) id from info group by `name` having count(`name`)>1 ) tmp
    )
    但这个办法,一次只能干掉重复数据的最大id,没关系,用循环嘛。
    多来几次,世界清爽了:

      id name
      1 张三
      2 李四
      3 麻婆
      4 王五

    再插入一次:INSERT INTO info(`name`) VALUE('麻老五');

      id name
      1 张三
      2 李四
      3 麻婆
      4 王五
      13 麻老五

    但且慢,麻老五的id值变成了13,应该是5才对啊。看看创建表的过程,原来是设置了自增字段,delete 清除了数据,但没有清除自增字段值。

    解决它:

    先删除掉刚刚插人的这行,

    查查现在有多少行:

    select count(id) from info

    重置自增字段偏移值为行数:
    alter table info AUTO_INCREMENT = 4

    现在再插入:INSERT INTO info(`name`) VALUE('麻老五');

      id name
      1 张三
      2 李四
      3 麻婆
      4 王五
      5 麻老五

    用pymysql实现上述过程,完整代码如下: 

    import pymysql

    conn = pymysql.connect(host='xx.xxx.xxx.x', port=3306, user='root', passwd='root123', charset="utf8", db='luffydb')
    cursor = conn.cursor()

    # 功能:循环删除重复数据,并修改自增字段偏移值为count(id)。

    sql = 'select max(id) from info group by `name` having count(`name`)>1'
    cursor.execute(sql)
    ret = cursor.fetchall() # 查询重复数据,但只取到重复数据的最大id,所以要用while循环,直到这个值为空。
    while ret:
    # 先删除查出的id
    cursor.execute(delete from info where info.id in
    (select tmp.id from
    (select max(id) id from info group by `name` having count(`name`)>1 ) tmp
    )
               )
    conn.commit()

    # 执行删除后再查询,重新获得ret值,供while判断。
    cursor.execute(sql)
    ret = cursor.fetchall()

    # 重置自增字段偏移值
    cursor.execute('select count(id) from info')
    ret = cursor.fetchone() # 查到现在的行数
    sql = 'alter table info AUTO_INCREMENT = %s'
    cursor.execute(sql, [ret[0]]) # 重置自增字段偏移值为行数。

    注意:mysql不支持,在一条语句对同一个表,先查询再更新的操作。所以要在'tmp'表外面再套一个表。否则报1093错误。




     
  • 相关阅读:
    AJAX异步传输——以php文件传输为例
    js控制json生成菜单——自制菜单(一)
    vs2010中关于HTML控件与服务器控件分别和js函数混合使用的问题
    SQL数据库连接到服务器出错——无法连接到XXX
    PHP错误:Namespace declaration statement has to be the very first statement in the script
    【LeetCode】19. Remove Nth Node From End of List
    【LeetCode】14. Longest Common Prefix
    【LeetCode】38. Count and Say
    【LeetCode】242. Valid Anagram
    【LeetCode】387. First Unique Character in a String
  • 原文地址:https://www.cnblogs.com/qqq789001/p/15046472.html
Copyright © 2011-2022 走看看