此篇记录了如何确定数据库中是否有重复的数据,如果有如何将重复的数据删除。
判断数据是否重复时,建议根据能够唯一确定一个对象的属性进行判断,比方说身份证号,一个学校的学生学号,手机号等信息。如果此类属性被确认在数据表中有重复的记录,那么可以确定此条记录重复。
以学生表为例,先用group by,having count 根据学生学号来找出重复的数据,然后将其删除。
学生信息表
根据学号(no)查出重复记录。
select no ,count(*) from student group by no having count(*)>1;
查出ID号较小的重复数据,将其删除,只保留ID号最大的数据。
要保留的数据
select min(id),no ,count(*) from student group by no having count(*)>1;
删除数据
select a.id,a.no,a.name from student a join(select max(id) as id,no ,count(*) from student group by no having count(*)>1)b on a.no = b.no and a.id<b.id;
delete a from student a join(select max(id) as id,no ,count(*) from student group by no having count(*)>1)b on a.no = b.no and a.id<b.id;
點擊查看更多內容
3人點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦