1. 程式人生 > >#oracle--刪除以id為主鍵地重複記錄,且只留下重複記錄中第一條記錄的sql語句

#oracle--刪除以id為主鍵地重複記錄,且只留下重複記錄中第一條記錄的sql語句

這道題是我面試一家金融軟體公司的筆試題,該題如下所示: 如下表,是一張使用者表,且uerid為主鍵,圖如下所示。 這裡寫圖片描述 要求能夠通過一個sql語句刪除所有重複的記錄,並只留下重複記錄中第一條記錄的sql語句。

答案:

delete from userinfo u3 where u3.userid in (               
  with aaa as(select u2.userid,u2.age,u2.email,u2.password,u2.sex,u2.tel,u2.username from userinfo u2,
  (select count(0),
      u.age
, u.email, u.password, u.sex, u.username, u.tel from userinfo u group by u.age, u.email, u.password, u.sex, u.username, u.tel having count(0) > 1) c where u2.age = c.age and u2.email = c.email and u2.password = c.password
and u2.sex = c.sex and u2.tel = c.tel and u2.username = c.username) select aaa.userid from aaa where aaa.userid not in( select min(a.userid) from aaa a group by a.age, a.email, a.password, a.sex, a.username, a.tel ) )

分析: 第一步:要想刪除重複的記錄,我們首先就必須先找出哪些記錄是重複的:

select count(0),
      u.age,
      u.email,
      u.password,
      u.sex,
      u.username,
      u.tel
  from userinfo u
  group by u.age,
         u.email,
         u.password,
         u.sex,
         u.username,
         u.tel
  having count(0) > 1

第二步: 在userinfo表中找出所有重複的記錄:

select u2.userid,u2.age,u2.email,u2.password,u2.sex,u2.tel,u2.username from userinfo u2,
  (select count(0),
      u.age,
      u.email,
      u.password,
      u.sex,
      u.username,
      u.tel
  from userinfo u
  group by u.age,
         u.email,
         u.password,
         u.sex,
         u.username,
         u.tel
  having count(0) > 1) c
  where u2.age = c.age
  and u2.email = c.email
  and u2.password = c.password
  and u2.sex = c.sex
  and u2.tel = c.tel
  and u2.username = c.username

第三步: 對主鍵以外的欄位通過分組找出第一條(userid最小)的那些記錄: select min(a.userid) from aaa a group by a.age, a.email, a.password, a.sex, a.username, a.tel 重複記錄中去除第三步中的記錄,得到剩下的記錄就是需要刪除的重複記錄,最終語句如下所示。

delete from userinfo u3 where u3.userid in (               
  with aaa as(select u2.userid,u2.age,u2.email,u2.password,u2.sex,u2.tel,u2.username from userinfo u2,
  (select count(0),
      u.age,
      u.email,
      u.password,
      u.sex,
      u.username,
      u.tel
  from userinfo u
  group by u.age,
         u.email,
         u.password,
         u.sex,
         u.username,
         u.tel
  having count(0) > 1) c
  where u2.age = c.age
  and u2.email = c.email
  and u2.password = c.password
  and u2.sex = c.sex
  and u2.tel = c.tel
  and u2.username = c.username)
  select aaa.userid from aaa where aaa.userid not in( 
    select min(a.userid) from aaa a
    group by a.age,
           a.email,
           a.password,
           a.sex,
           a.username,
           a.tel             
   )     
)