删除sql语句的代码冗余

删除sql语句的代码冗余

首先我们先看一个问题实例
一、学生表记录如下(学号 姓名 性别 年龄)

  • 0001 xw 男 18
  • 0002 mc 女 16
  • 0003 ww 男 21
  • 0004 xw 男 18

请写出实现如下功能的SQL语句
删除除了学号(自动编号)字段以外,其他字段都相同的冗(rong)余记录
在mysql中我们怎么去实现这个记录呢

创建一个名为day02的数据库

create database day02;

创建学生表以及添加相应的字段(主键,学号,姓名,性别,年龄)

 use day0214;
 create table student(id int auto_increment primary key,code varchar(20),name varchar(20),sex varchar(20),age int);

在这里或许因为你的mysql版本问题会出现数据添加失败,不要担心,只是编码问题。

set character_set_client=gbk;  
set character_set_results=gbk;

再把数据添加进去

insert into student(code,name,sex,age)values("0001","xw","男",18),("0002","mc","女",16),("0003","ww","男",21),("0004","xw","男",18);

可以查看表的数据

select * from student

就会呈现出:
±—±-----±-----±-----±-----+
| id | code | name | sex | age |
±—±-----±-----±-----±-----+
| 1 | 0001 | xw | 男 | 18 |
| 2 | 0002 | mc | 女 | 16 |
| 3 | 0003 | ww | 男 | 21 |
| 4 | 0004 | xw | 男 | 18 |
±—±-----±-----±-----±-----+
在这里我们新建一个临时表,找出除了id之外的其他重复字段

create table tmp as(select t1.id,t1.code,t1.name,t1.sex,t1.age from student t1,(select min(id) as mid,code,name,sex,age from student group by name,sex,age having count(*)>1)t2 where t1.name=t2.name and t1.sex=t2.sex and t1.age=t2.age and t1.id>t2.mid);

从学生表中删除临时表里重复的字段的id

delete from student where id in (select id from tmp);

再查询临临时表

 select *from tmp;

直接删除临时表

drop table tmp;

到这里基本就完成了,希望对各位伙伴有所帮助

猜你喜欢

转载自blog.csdn.net/WJL0104/article/details/87260018