1. 程式人生 > >MySql 5.7匯入BOM資料後增加數字標識(id)及刪除重複資料

MySql 5.7匯入BOM資料後增加數字標識(id)及刪除重複資料

該表是Bom表,資料量很大,從Excel匯入的。當時由於時間關係,沒有在Excel中去重,就匯入了。
之前沒有意識到標識欄位的重要性,所以在建表時沒有設該欄位。
今天發現有重複資料,於是就想辦法去重。
表字段,bitem(商品),item(物料),qty,lvl 。
修改表結構

alter table t1 add col1 int default 0 not null 

給現有col1標識

set @rown:=0
update t1 set col1=(@rown:[email protected]+1) where col1=0

現在有唯一標識(id)了,可以去重

delete from t1 where col1 in 
( select a.col1 from (
    select max(col1) as col1 from t1  group by bitem,item having count(*) >1 
    ) as a
);
刪除重複資料成功

是不是複雜點,為啥不用

delete from t1 where col1 in 
    (select max(col1) as col1 from t1  group by bitem,item having count(*) >1  );
  這個語句在MSSQL中是對的,在MySql5.7中會報錯

因為會碰到You can’t specify target table for update in FROM clause錯誤,就是在更新的時候篩選子集和目標表不能一樣。
同樣情況會發生在update 用法中.

對於無標識id而要顯示行號,也可以用如下命令

select (@row:[email protected]+1) as no , a.* from t1 a, (select @row:=0), t;