MySQL查询数据表某列数值重复的记录并删除多余记录

chosen1cwp 2022年07月08日 25次浏览

数据库表中数据项有重复,需要删除其中多余的记录,保留一条记录即可,除了主键ID不同外,所有其他字段值都相同。

如下图所示:

Pasted Graphic

一、查询数据表中某列数值重复的记录

查询wage_result表中agent_code字段值相同的记录

SELECT
	id as ‘主键ID’,
	agent_code,
	COUNT(*) AS num — 重复数
FROM
	wage_result 
WHERE
	index_calno = '202204' 
	AND del_flag = '0' 
GROUP BY
	agent_code 
HAVING
	num > 1;

Pasted Graphic 1

二、删除重复项

Copy id 这一列,拼装为:‘1526767272776182098’,‘1526767272776182097’,‘1526767272776182101’

然后 DELETE 即可

DELETE FROM wage_result WHERE id IN 
(
'1526767272776182048','1526767272776182047','1526767272776182046','1526767272776182045','1526767272776182044','1526767272776182043','1526767272776182042','1526767272776182041','1526767272776182040','1526767272776182039''
);

Pasted Graphic 2