MySQL 大批量插入,如何过滤掉重复数据?
加班原因是上线,解决线上数据库存在重复数据的问题,发现了程序的bug,
很好解决,有点问题的是,修正线上的重复数据。
CREATE TABLE `animal` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
INSERT INTO `pilipa_dds`.`student` (`id`, `name`, `age`) VALUES ('1', 'cat', '12');
INSERT INTO `pilipa_dds`.`student` (`id`, `name`, `age`) VALUES ('2', 'dog', '13');
INSERT INTO `pilipa_dds`.`student` (`id`, `name`, `age`) VALUES ('3', 'camel', '25');
INSERT INTO `pilipa_dds`.`student` (`id`, `name`, `age`) VALUES ('4', 'cat', '32');
INSERT INTO `pilipa_dds`.`student` (`id`, `name`, `age`) VALUES ('5', 'dog', '42');
SELECT name,count( 1 )
FROM
student
GROUP BY
NAME
HAVING
count( 1 ) > 1;
name count(1) cat 2 dog 2
Select * From 表 Where 重复字段 In (Select 重复字段 From 表 Group By 重复字段 Having Count(1)>1)
删除全部重复数据,一条不留
DELETE
FROM
student
WHERE
NAME IN (
SELECT NAME
FROM
student
GROUP BY
NAME
HAVING
count( 1 ) > 1)
1093 - You can't specify target table 'student' for update in FROM clause, Time: 0.016000s
DELETE
FROM
student
WHERE
NAME IN (
SELECT
t.NAME
FROM
( SELECT NAME FROM student GROUP BY NAME HAVING count( 1 ) > 1 ) t)
删除表中删除重复数据,仅保留一条
SELECT
*
FROM
student
WHERE
id NOT IN (
SELECT
t.id
FROM
( SELECT MIN( id ) AS id FROM student GROUP BY `name` ) t
)
开始删除重复数据,仅留一条
DELETE
FROM
student
WHERE
id NOT IN (
SELECT
t.id
FROM
( SELECT MIN( id ) AS id FROM student GROUP BY `name` ) t
)
逆锋起笔
是一个专注于程序员圈子的技术平台,你可以收获最新技术动态
、最新内测资格
、BAT等大厂的经验
、精品学习资料
、职业路线
、副业思维
,微信搜索逆锋起笔
关注!
觉得不错,请点个在看
评论