如何使用脚本在同一个表中查找重复数据

时间:2012-03-22 07:43:34

标签: sql

我需要在USERS表中精确复制用户,并将user_id和重复的user_id插入到不同的表中。 我构建了这个脚本,我不知道它有什么问题。

BEGIN
FOR  v_user IN ( 
                  SELECT u.*
                  FROM users u
                  )
loop
       FOR v_dupUser IN (
                           SELECT u.*
                           FROM users u
                           WHERE u.email = v_user.email
                                 OR u.mobile_phone = v_user.mobile_phone
                                 OR u.land_line_phone = v_user.mobile_phone
                           )
       loop
           INSERT INTO DUPLICATES_USERS(id, user_id, dup_user_id,time_created) 
           VALUE (SEQ_DUPLICATED_USERS, v_user.id, v_DupUser,SYSDATE);
       end loop;
end loop;
END;

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我会更喜欢沿着这样的道路走下去;

insert into duplicated_users
 (select a.user_id user_id,
 b.user_id dup_user_id
 from users a
  , users b
 where (a.email = b_user.email
   OR a.mobile_phone = b_user.mobile_phone
   OR a.land_line_phone = b_user.mobile_phone)
  and a.user_id != b.user_id);

答案 1 :(得分:0)

我认为您必须使用以下查询。

insert into duplicated_user 
(
    select * from [USER] where 
       user_id in (select user_id 
                     from [USER] 
                     group by user_id having count(user_id) > 1)
)