sql刪除多個字段重複數據有主鍵和沒主鍵解決方法(mysql)

table user
     name age nub
     張三    12  23
     張三    12  23
     張三    12  23
     李四    13  21
     李四    13  21
     王五    11  25sql

查詢重複記錄(一條)
sql:select * from user group by name,age,nub having count(*)>1;
    (如需統計條數請使用conut)table

set:
     name age nub
     張三   12  23
     李四   13  21select

查詢重複記錄(全部)sql語句

sql:select * from user  a where (a.name,a.age,a.nub)  in (select *  from user group by name,age,nub having count(*)>1);統計

set
     name age nub
     張三   12   23
     張三   12  23
     張三   12  23
     李四   13  21
     李四   13  21數據

刪除重複記錄保留一條
 步驟:
     1.將查詢的數據插入一個新的表中;
     2.刪除原來的表的數據
     3.將新表的數據再插入原表中
     4,刪除新表查詢

 sql:
     1. create table new_table (select * from user group by name,age,nub having count(*)>1);
 
     2.delete from user  a where (a.name,a.age,a.nub)  in
       (select * from
       (select *  from user group by name,age,nub having count(*)>1) as b );tab

       在這裏使用了兩次select 由於:vi

       delete from user  a where (a.name,a.age,a.nub)  in
       (select *  from user group by name,age,nub having count(*)>1);會出現錯誤    
 co

       不能對同一表子查詢後進行插入或者刪除 要在子查詢再嵌套一個查詢 讓對該表查詢成爲孫查詢;
 
     3.insert into user (select name,age,nub from new_table);
 
      注意:在插入數據的時候查詢表獲得字段的順序要與原表相同否者會出現數據錯誤;
      若是原表數據順序與新表相同能夠用這條語句insert into user (select * from new_table);

     4.drop table new_table;


到此完成操做 最後的數據:


     table user

          name age nub
          張三   12   23
          李四   13   21
          王五   11   25


若是原表中含有主鍵的話更好操做
 不用四條sql語句了 直接執行刪除操做
 delete from user  a where (a.name,a.age,a.nub)  in
   (select name,age,nub from
   (select *  from user group by name,age,nub having count(*)>1) as b  )
   and id not in(select min(id) from
   (select *  from user group by name,age,nub having count(*)>1) as c);

 

注意事項: 在使用 (name,age,address) in (select *)的時候 * 只能是三列 若是有更多列則不能使用 *,要明確指出是哪些列;

相關文章
相關標籤/搜索