MySQL根据某一个或者多个字段查找/删除重复数据

1、根据一个字段找到重复记录
SELECT * FROM table WHERE 字段 IN (
 SELECT 字段 FROM tb_table GROUP BY 字段 HAVING COUNT(字段) > 1
);
2、根据字段1和字段2字段找到重复记录
SELECT * FROM (SELECT *, CONCAT(字段1,字段2) as 字段1And字段2 FROM table) a WHERE a.字段1And字段2 IN (
 SELECT 字段1And字段2 FROM (SELECT CONCAT(字段1,字段2) as 字段1And字段2 FROM table) b GROUP BY 字段1And字段2 HAVING COUNT(字段1And字段2) > 1
)
3、删除某个字段重复记录,只保留id字段值最大的记录
DELETE FROM table WHERE id not IN (
 SELECT maxid FROM (SELECT max(id) as maxid FROM table group by 字段) b
);
4、删除多个字段重复记录,只保留id字段值最大的记录
DELETE FROM table WHERE id not IN (
 SELECT maxid FROM (SELECT MAX(id) as maxid, CONCAT(字段1,字段2) as 字段1And字段2 FROM table GROUP BY 字段1And字段2) t
);

您可以选择一种方式赞助本站

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: