MySQL根据某一个或者多个字段查找重复数据的sql语句
16lz
2021-12-25
sql 查出一张表中重复的所有记录数据
1.表中有id和name 两个字段,查询出name重复的所有数据
select * from xi a where (a.username) in (select username from xi group by username having count(*) > 1)
select count(username) as '重复次数',username from xi group by username having count(*)>1 order by username desc
1、查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断
select * from peoplewhere peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
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)
select * from vitae awhere (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
delete from vitae awhere (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)
select * from vitae awhere (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)
比方说
在A表中存在一个字段“name”,
而且不同记录之间的“name”值有可能会相同,
现在就是需要查询出在该表中的各记录之间,“name”值存在重复的项;
Select Name,Count(*) From A Group By Name Having Count(*) > 1
Select Name,sex,Count(*) From A Group By Name,sex Having Count(*) > 1
方法一
declare @max integer,@id integerdeclare cur_rows cursor local for select 主字段,count(*) from 表名 group by 主字段 having count(*) >;open cur_rows fetch cur_rows into @id,@maxwhile @@fetch_status=0begin select @max = @max -1 set rowcount @max delete from 表名 where 主字段 = @idfetch cur_rows into @id,@maxendclose cur_rowsset rowcount 0
1、对于第一种重复,比较容易解决,使用
select distinct * from tableName
如果该表需要删除重复的记录(重复记录保留1条),
可以按以下方法删除
select distinct * into #Tmp from tableNamedrop table tableNameselect * into tableName from #Tmpdrop table #Tmp
2、这类重复问题通常要求保留重复记录中的第一条记录,操作方法如下 假设有重复的字段为Name,Address,要求得到这两个字段唯一的结果集
select identity(int,1,1) as autoID, * into #Tmp from tableNameselect min(autoID) as autoID into #Tmp2 from #Tmp group by Name,autoIDselect * from #Tmp where autoID in(select autoID from #tmp2)
(四)查询重复
select * from tablename where id in (select id from tablenamegroup by idhaving count(id) > 1)
根据sample_code字段找到重复记录
SELECT * FROM tb_table WHERE sample_code IN( SELECT sample_code FROM tb_table GROUP BY sample_code HAVING COUNT(sample_code) > 1 );
根据name和code字段找到重复记录
SELECT * from (SELECT *, CONCAT(name,code) as nameAndCode from tb_table) t WHERE t.nameAndCode in ( SELECT nameAndCode from (SELECT CONCAT(name,code) as nameAndCode from tb_table) tt GROUP BY nameAndCode HAVING count(nameAndCode) > 1)
更多相关文章
- python list.sort()根据多个关键字排序的方法实现
- android 当系统存在多个Launcher时,如何设置开机自动进入默认的La
- Android(安卓)初识Retrofit
- 【android】监听网络变化连续多个广播的问题解决
- android图片上传springMvc
- android 之simpleAdapter详解
- android sqlite 一次创建多个表
- Android(安卓)微博登录
- Android中读取电话本Contacts联系人的所有电话号信息