Oracle查询表里重复数据

一、查询结果只显示重复的字段

1. 查询重复的单个字段(group by)

select 重复字段A, count(*)
  from 表
 group by 重复字段A
having count(*) > 1

2.查询重复的多个字段(group by)

select 重复字段A, 重复字段B, count(*)
  from 表
 group by 重复字段A, 重复字段B
having count(*) > 1

二、查询结果显示重复数据的所有字段

1.查询重复的单个字段( rowid)

-- table a,table b  代表同一张表 
select a.*
   from table a, table b
  where a.重复字段 = b.重复字段
    and a.rowid != b.rowid
  order by a.重复字段

排序是为了更直观的比较多个重复数据

2.查询重复的多个字段( rowid)

--  table a, table b 代表同一张表
select a.*
   from table a, table b
  where a.重复字段A = b.重复字段A
    and a.重复字段B = b.重复字段B
    and a.rowid != b.rowid
  order by a.重复字段A

三、删除重复数据

1.删除重复数据中rowid 最小的数据

-- 先查出来看一眼  table a,table b 属于同一张表  rowid 最小的数据
select *
  from table a
 where rowid != (select max(rowid)
                   from table b
                  where a.重复字段 = b.重复字段)

-- 删除这部分数据  rowid 最小的数据

delete from table a
 where rowid != (select max(rowid)
                   from table b
                  where a.重复字段 = b.重复字段)

2.删除重复数据中rowid 最大的数据

-- 先查出来看一眼  table a,table b 属于同一张表  rowid 最大的数据
select *
  from table a
 where rowid != (select min(rowid)
                   from table b
                  where a.重复字段 = b.重复字段)

-- 删除这部分数据  rowid 最大的数据

delete from table a
 where rowid != (select min(rowid)
                   from table b
                  where a.重复字段 = b.重复字段)

3.删除所有重复的数据

-- 慎重考虑后执行,后悔记得及时回滚。

delete from table group by 重复字段 having count(重复字段) > 1

注意:如果误删了数据,请看这里

回滚也不管用了,记得点这个链接,找回刚才删除的数据

猜你喜欢

转载自blog.csdn.net/loveLifeLoveCoding/article/details/85156946
今日推荐