Mysql刪除表中重複資料

2021-10-14 11:23:11 字數 956 閱讀 6334

一張表中有重複資料,需要刪除重複的資料,只保留(最大/最小)一條。

例:現有a表:

id:主鍵(唯一)

b:資料(有重複)

需求:刪除表中重複的資料,保留相同資料中id最小的資料。

效果:

sql思路:先查詢出去重過後的id(可用分組),再刪除其它id的資料

delete from a where	id not in ( select id from ( select	min(id) as id from a group by b ) c );
sql解釋
delete

from

a # 表a

where

id not in ( # 需要刪除資料的id,不包含下面查詢出來的id

select # 此條select查詢不可省,否則報錯:you can't specify target table 'a' for update in from clause。

# 內層select分組後,再次查詢c表獲得id

idfrom

(select

min(id) as id # 保留相同資料中,id最小的資料。as不可省,命名別名為id。

# 若省略,執行2個select報錯:unknown column 'id' in 'field list'。

# 整體語句執行不會報錯,但無效果。

from

agroup by

b) c # 此處的c,不可省。分組後的資料,生成表c,外層select查詢c表,獲取最終的id

);

刪除表中重複資料

刪除表中重複資料 取出line fancy2表中fancy name相同的最小fancy id 寫進tmp表 create table tmp as select min fancy id as col1 from line fancy2 group by fancy name 刪除line fan...

刪除表中重複資料

如果重複資料很多,被刪掉的可能是大部分記錄,業務又允許的情況下,可以考慮重建表 create table newtable as select distinct from table rename table to oldtable rename newtable to table create i...

Oracle刪除表中重複資料

1.建立臨時表 備份全部資料到 create table tmap.t comm customer col log 731all as select from tmap.t comm customer col log 2.建立臨時表 備份資料 去除重複項 create table tmap.t co...