#以下測試表b,如何刪除重複值字段:測試
SQL> select * from b1; it
ID NAMEtable
---------- ---------- select
1 a 語法
1 a 方法
1 b 數據
2 a查詢
1 a
2 atab
#小結:重複值多:則重建表更好、 重複值少,表大,則delete更好vi
#方法一:
group by 分組,找到有效數據,建立一個新表,數據插入,隨後刪除原表,隨後rename 該名稱:
SQL> create table b2 as select * from b1 group by id,name;
SQL> select * from b2;
1 a 1 b 2 a
SQL> drop table b1 purge;
SQL> alter table b2 rename to b1;
#方法二:
找出不符合規則的數據,delete刪除
SQL> select rowid,id,name from b1 where (id,name) in(select id,name from b1 having(count(*))>1 group by id,name);
ROWID ID NAME
------------------ ---------- ----------
AAAV3EAAEAAAAKTAAA 1 a
AAAV3EAAEAAAAKTAAB 1 a
AAAV3EAAEAAAAKTAAD 2 a
AAAV3EAAEAAAAKWAAE 1 a
AAAV3EAAEAAAAKWAAF 2 a
#本想經過rownum,最後仍是選擇rowid 惟一
#查詢符合條件的ROWID:重複行數據中,最小的rowid的value
SQL> select min(rowid) from b1 group by id,name having(count(*))>1;
MIN(ROWID) ------------------
AAAV3EAAEAAAAKTAAA
AAAV3EAAEAAAAKTAAD
#刪除語法:由於若是表沒有任何列是惟一的,那麼最好直接使用rowid,穩定惟一:
找到全部重複記錄的value, 排除重複記錄中,最小的rowid 保留一行
SQL> delete from b1
where rowid in
(select rowid from b1 where (id,name)
in(select id,name from b1 having(count(*))>1 group by id,name))
and rowid not in
(select min(rowid) from b1 having(count(*))>1 group by id,name);
3 rows deleted.
SQL> select * from b1;
ID NAME ---------- ----------
1 a 1 b 2 a
SQL> commit;