1、查找重复记录
①如果只是不想在查询结果中存在重复记录, 可以加distinct
select distinct * from testtable
②如果是想查询重复的记录及其数量
select userid,username,count(*) as ‘记录数’
from testtable
group by userid,username
having count(*)>1
③id不重复, 但是字段重复的记录只显示一条
select * from testtable where userid in
(select max(userid) as userid from testtable group by username,sex,place)
2、删除重复记录
①一种思路是利用临时表, 把查询到的无重复记录填充到临时表, 再把临时表的记录填充回原始表
select distinct * into #temp from testtable
drop table testtable
select * into testtable from #temp
drop table #temp
②删除id不重复, 但是字段重复的记录(就是按字段查询出相同字段记录中最大的id,然后保留此记录, 删除其他记录).(group by 的字段, 有点麻烦).
delete testtable where userid not in
(select max(userid) as userid from testtable group by username,sex,place)