zoukankan      html  css  js  c++  java
  • Mysql删除重复记录,保留id最小的一条

    原文链接:https://www.cnblogs.com/youxin/p/6380234.html

    1、查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断

    select * from people
    where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)

    2、删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有rowid最小的记录

    delete from people
    where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
    and rowid not in (select min(rowid) from people group by peopleId having count(peopleId )>1)

    (上面这条语句在mysql中执行会报错:


    执行报错:1093 - You can't specify target table 'student' for update in FROM clause
    原因是:更新数据时使用了查询,而查询的数据又做了更新的条件,mysql不支持这种方式。oracel和msserver都支持这种方式。
    怎么规避这个问题?
    再加一层封装,

    delete from php_user where 
    username in (select username from ( select username from php_user group by username having count(username)>1) a) 
    and id not in ( select min(id) from (select min(id) as id from php_user group by username having count(username)>1 ) b)

     注意select min(id) 后面要有as id.

  • 相关阅读:
    .NET实时2D渲染入门·动态时钟
    JAVA中抽象类的使用
    R语言中函数调试
    利用Bioperl的SeqIO模块解析fastq文件
    ASCII码表
    JAVA 中转义符的理解
    在线引物设计网站,老板推荐的,亲测好用
    列出一个买东西的好网站,值得推荐
    R语言集合操作
    R语言do.call 函数用法详解
  • 原文地址:https://www.cnblogs.com/fswhq/p/Mysql_delete.html
Copyright © 2011-2022 走看看