与我的两个sql在Oralce中找到重复记录的区别是什么?

时间:2016-08-19 01:57:33

标签: sql oracle oracle11g

如果记录重复,我想删除并只留下一条记录。在我的表中,t_id是一个主键,它是int类型,自动递增,id是序列号,是varchar类型。 起初,我的sql就是这样。但它看起来像死锁,并且运行很长时间,似乎永远不会停止。

delete from tbtest
Where t_id Not In (
select max(t_id) from tbtest having count(id)>1  
group by id
 )
and  id in (
select id   from tbtest group by id having count(id)>1 
) 
and create_time<to_timestamp('2016-02-25 11:26:52','yyyy-mm-dd hh24:mi:ss') 

所以我把它换成另一种方式,它运行得非常快?它们之间的区别是什么?

delete from tbtest where t_id in (
 select  t_id   from tbtest 
Where t_id Not In (
select max(t_id) from tbtest having count(id)>1  
group by id
)
and  id in (
select id   from tbtest group by id having count(id)>1 
) 
and create_time<=to_timestamp('2016-02-25 11:26:52','yyyy-mm-dd hh24:mi:ss') 
)

1 个答案:

答案 0 :(得分:2)

这是一个概念证明。试一试,看看它是否有帮助。

create table ta ( t_id number primary key, id varchar2(10), val number );

insert into ta 
    select 1, '1', 33 from dual union all
    select 2, '2', 44 from dual union all
    select 3, '2', 55 from dual;

commit;

select * from ta;

      T_ID ID                VAL
---------- ---------- ----------
         1 1                  33
         2 2                  44
         3 2                  55

delete from ta
where t_id in (select t_id from (select t_id, id, 
      row_number() over (partition by id order by t_id desc) rn from ta) where rn > 1);

1 row deleted.

select * from ta;

      T_ID ID                VAL
---------- ---------- ----------
         1 1                  33
         3 2                  55