• 删除重复记录,只保留一条信息


    效果如下图:

    ---结果:----》

    1.创建学生表:

    CREATE TABLE `student` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `sname` varchar(10) DEFAULT NULL,
      `gender` varchar(4) NOT NULL DEFAULT '',
      `age` int(3) DEFAULT '20',
      `class_id` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    )

    2.插入测试数据

    INSERT INTO `student` VALUES (2,'马继','',18,1),(3,'张孟','',23,1),(12,'吴昊','',25,0),(13,'肖新露','',25,0),(14,'米少东','',23,0),(15,'白乾亮','',20,0),(16,'米少东','',23,0),(17,'白乾亮','',20,0),(18,'米少东','',23,0);

    3.sql分解语句:

         #1查询重复学生的姓名

    select sname from student group by sname having count(sname)>1

        #2查询重复学生中最小id。

    select min(id) from student group by sname having count(sname)>1

       #3查询重复姓名的id---并且---不包含重复姓名最小id

    select id from student where 
                sname in(select sname from student group by sname having count(sname)>1)
                and 
                id not in(select min(id) from student group by sname having count(sname)>1)

      # 4这里需要将 运行出来的结果,作为一个临时表。否则会报:You can't specify target ‘student’ for update in FROM clause(这个错误的意思是不能在同一表中查询的数据作为同一表的更新数据)。

              错误语句为:    

    delete from student where id in ( 
         select id from student where 
                sname in(select sname from student group by sname having count(sname)>1)
                and 
                id not in(select min(id) from student group by sname having count(sname)>1)
    )#错误语句:报错--You can't specify target ‘student’ for update in FROM clause

             正确语句为:

    delete from student where id in ( 
      select * from 
        (select id from student where 
                sname in(select sname from student group by sname having count(sname)>1)
                and 
                id not in(select min(id) from student group by sname having count(sname)>1)
        ) as mysu
    )

     最终结果为:

  • 相关阅读:
    【leetcode】1103. Distribute Candies to People
    【leetcode】1074. Number of Submatrices That Sum to Target
    【leetcode】1095. Find in Mountain Array
    【leetcode】1094. Car Pooling
    2018.9.27 长难句1
    L142
    L141
    L140
    Agilent RF fundamentals (11)-Vector modulator
    Agilent RF fundamentals (10) Mixer ,Phase domain and modulator
  • 原文地址:https://www.cnblogs.com/wu-chao/p/8395697.html
Copyright © 2020-2023  润新知