sql 删除表中多余的重复记录(多个字段)

delete语句

删除表中多余的重复记录(多个字段),只留有rowid最小的记录

在网上搜索了一个mysql数据库删除重复数据的sql,原文是这样的:

delete from vitae a where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)

参考上面sql,修改如下:

delete from t_total_electricity_station a
where (a.same_day,a.dev_id) in (select  es.same_day,es.dev_id  from t_total_electricity_station es  group by  es.same_day,es.dev_id  having count(*) > 1)
and a.id not in (select min(id) as id from t_total_electricity_station group by same_day,dev_id having count(*)>1)

运行之后报错,查找delete注意点,找到如下:

若是delete from表和子查询使用了同一张表就会出错,修改如下sql:

DELETE from t_total_electricity_station a
where (a.same_day,a.dev_id) in (select  es.same_day,es.dev_id  from (SELECT * FROM t_total_electricity_station) as es  group by  es.same_day,es.dev_id  having count(*) > 1)
and a.id not in (select min(dd.id) as id from(SELECT * FROM t_total_electricity_station) as dd group by dd.same_day,dd.dev_id having count(*)>1)

执行之后依然报错,继续查找

delete from table 后面的table不能使用别名,最后修改成执行成功语句:

delete from t_total_electricity_station  where (same_day,dev_id) in (select xx.same_day,xx.dev_id from (select * from t_total_electricity_station) xx group by xx.same_day,xx.dev_id having count(*) > 1) and id not in (select min(dd.id) from (select * from t_total_electricity_station) dd group by dd.same_day,dd.dev_id having count(*)>1)

参考:

MySQL之——查询重复记录、删除重复记录方法大全_珂-瑞的博客-CSDN博客_mysql查询重复数据只保留一条

mysql delete 子查询 语法错误_小小鱼er的博客-CSDN博客

感谢!!

你可能感兴趣的:(javaweb,sql,数据库,mysql)