MySQL和Oracle关于重复数据的操作(查找、删除)

假设有employee这张表,其中emp_name可能有重复,emp_id是主键(没有主键的写法在最后)

以下是MySQL和Oracle中关于重复数据的删除查找操作


查询重复数据:

Oracle、MySQL

select * from employee group by emp_name having count (*)>1;


查询可以删除的重复数据:

Oracle:

select t1.* from employee t1 where 
t1.emp_name in 
(SELECT t2.emp_name from employee t2 group by emp_name having count (*)>1) 
and 
t1.emp_id not in
(select min(t3.emp_id) from employee t3 group by emp_name having count (*)>1);
MySQL:

select t1.* from employee t1 where 
t1.emp_name in 
(select t4.emp_name from (select t2.emp_name from employee t2 group by t2.emp_name having count(*)>1) t4) 
and
t1.emp_id not in 
(select t5.emp_id from (select min(t3.emp_id) as emp_id from employee t3 group by t3.emp_name having count(*)>1) t5);

删除重复数据:

Oracle:

delete t1 from employee t1 where 
t1.emp_name in 
(SELECT t2.emp_name from employee t2 group by emp_name having count (*)>1) 
and
t1.emp_id not in 
(select min(t3.emp_id) from employee t3 group by emp_name having count (*)>1);

MySQL:

delete t1 from employee t1 where 
t1.emp_name in 
(select t4.emp_name from (select t2.emp_name from employee t2 group by t2.emp_name having count(*)>1) t4) 
and 
t1.emp_id not in 
(select t5.emp_id from (select min(t3.emp_id) as emp_id from employee t3 group by t3.emp_name having count(*)>1) t5);

没有主键的情况下删除重复记录是面试时经常会问到的,此时Oracle和MySQL的处理方法也有所不同。

Oracle:

主要利用了rowid,rowid它是Oracle的一个伪列,它并不实际存在于表中。它是ORACLE在读取表中数据行时,根据每一行数据的物理地址信息编码而成的一个伪列。我们可以把它当成一条记录的唯一标识来使用。只保留一个rowid最大或者最小的记录即可。如果主键是number类型,也可以使用这种方法,把rowid换成主键名即可。

delete from employee t1 where
t1.rowid > 
(select min(t2.rowid) from employee t2 where t1.emp_name=t2.emp_name);

MySQL:

MySQL没有类似Oracle的rowid,所以操作会比较麻烦。

1.查询重复记录,将查询的数据插入一个新的表中
2.删除原来的表的重复数据
3.将新表的数据再插入原表中
4.删除新表

create table new_table
(select * from employee group by emp_name having count(*)>1);

delete employee.* from employee where emp_name in
(select t.* from
(select emp_name from employee group by emp_name having count(*)>1) t);
第二步这里查出的重复数据需要嵌套一层查询。如果先查出同一表中的某些值,再修改这个表的内容(在同一语句中)会出现 You can't specify target table 的错误。

insert into employee (select * from new_table);
drop table new_table;




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值