MySQL 删除数据库中重复数据方法小结
网络编程 2021-07-05 15:27www.168986.cn编程入门
在实际项目中,我们经常会遇到删除数据库中重复数据的问题,貌似是很简单的问题哈,狼蚁网站SEO优化我们来探讨下
刚开始,根据我的想法,这个很简单嘛,上sql语句
delete from zqzrdp where tel in (select min(dpxx_id) from zqzrdp group by tel having count(tel)>1);
执行,报错!!~!~
异常意为你不能指定目标表的更新在FROM子句。傻了,MySQL 这样写,不行,让人郁闷。
难倒只能分步操作,蛋疼
以下是网友写的,同样是坑爹的代码,我机器上运行不了。
1. 查询需要删除的记录,会保留一条记录。
select a.id,a.subject,a.RECEIVER from test1 a left join (select c.subject,c.RECEIVER ,max(c.id) as bid from test1 c where status=0 GROUP BY RECEIVER,SUBJECT having count(1) >1) b on a.id< b.bid where a.subject=b.subject and a.RECEIVER = b.RECEIVER and a.id < b.bid
2. 删除重复记录,只保留一条记录。注意,subject,RECEIVER 要索引,否则会很慢的。
delete a from test1 a, (select c.subject,c.RECEIVER ,max(c.id) as bid from test1 c where status=0 GROUP BY RECEIVER,SUBJECT having count(1) >1) b where a.subject=b.subject and a.RECEIVER = b.RECEIVER and a.id < b.bid;
3. 查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断
select from people where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
4. 删除表中多余的重复记录,重复记录是根据单个字段(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)
5.删除表中多余的重复记录(多个字段),只留有rowid最小的记录
delete from vitae a where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count() > 1) and rowid not in (select min(rowid) from vitae group by peopleId,seq having count()>1)
看来想偷懒使用一句命令完成这个事好像不太显示,还是老老实实的分步处理吧,思路先建立复制一个临时表,然后对比临时表内的数据,删除主表里的数据
alter table tableName add autoID int auto_increment not null; create table tmp select min(autoID) as autoID from tableName group by Name,Address; create table tmp2 select tableName. from tableName,tmp where tableName.autoID = tmp.autoID; drop table tableName; rename table tmp2 to tableName;
编程语言
- 如何快速学会编程 如何快速学会ug编程
- 免费学编程的app 推荐12个免费学编程的好网站
- 电脑怎么编程:电脑怎么编程网咯游戏菜单图标
- 如何写代码新手教学 如何写代码新手教学手机
- 基础编程入门教程视频 基础编程入门教程视频华
- 编程演示:编程演示浦丰投针过程
- 乐高编程加盟 乐高积木编程加盟
- 跟我学plc编程 plc编程自学入门视频教程
- ug编程成航林总 ug编程实战视频
- 孩子学编程的好处和坏处
- 初学者学编程该从哪里开始 新手学编程从哪里入
- 慢走丝编程 慢走丝编程难学吗
- 国内十强少儿编程机构 中国少儿编程机构十强有
- 成人计算机速成培训班 成人计算机速成培训班办
- 孩子学编程网上课程哪家好 儿童学编程比较好的
- 代码编程教学入门软件 代码编程教程