mysql刪除多個重複數據,多個字段添加惟一性索引

需求:刪除station_id、ab_data_time、item_code_id、data_cycle、ab_value 字段重複的記錄sql

 

#查詢重複的數據ruby

select 
  b.id,b.station_id,b.ab_data_time,b.item_code_id,b.data_cycle,b.ab_lable,b.ab_value
from 
d_abnormal_data_yyyymms b
where
(b.station_id,b.ab_data_time,b.item_code_id,b.data_cycle,b.ab_value) in (
    select * 
    from
    (
    select 
        station_id,ab_data_time,item_code_id,data_cycle,ab_value
     from
         d_abnormal_data_yyyymms
      group by
          station_id,ab_data_time,item_code_id,data_cycle,ab_value
      having 
          count(*) >1
    ) b
)
and ab_data_time <= '2019-01-22 12:00:00';

 

#刪除多個字段重複數據(去掉ab_lable字段)spa

delete 
from 
d_abnormal_data_yyyymms
where
(station_id,ab_data_time,item_code_id,data_cycle,ab_value) in (
    select * 
    from
    (
    select 
        station_id,ab_data_time,item_code_id,data_cycle,ab_value
     from
         d_abnormal_data_yyyymms
      group by
          station_id,ab_data_time,item_code_id,data_cycle,ab_value
      having 
          count(*) >1
    ) b
)
and 

ab_data_time <= '2019-01-22 12:00:00'

and

id not in

(select * from 

(select 
min(id) 
from 
	d_abnormal_data_yyyymms 
where 

ab_data_time <=  '2019-01-22 12:00:00' 

group by 
	station_id,ab_data_time,item_code_id,data_cycle,ab_value
having count(*)>1)c
);

  

#查看數據是否還保留一條code

select 
  b.id,b.station_id,b.ab_data_time,b.item_code_id,b.data_cycle,b.ab_lable,b.ab_value
from 
d_abnormal_data_yyyymms b
where
ab_data_time = '2018-12-17 11:50:00';

 

#添加惟一索引orm

create unique index station_id_time_code_cycle_lable_value on d_abnormal_data_yyyymms(station_id,ab_data_time,item_code_id,data_cycle,ab_lable,ab_value);
相關文章
相關標籤/搜索