MySQL 大批量插入,如何过滤掉重复数据?
线上库有6个表存在重复数据,其中2个表比较大,一个96万+、一个30万+,因为之前处理过相同的问题,就直接拿来了上次的Python去重脚本,脚本很简单,就是连接数据库,查出来重复数据,循环删除。
CREATETABLE`animal` (
`id`int(11) NOTNULL AUTO_INCREMENT,
`name`varchar(20) DEFAULTNULL,
`age`int(11) DEFAULTNULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1DEFAULTCHARSET=utf8 COLLATE=utf8_bin;
INSERTINTO`pilipa_dds`.`student` (`id`, `name`, `age`) VALUES ('1', 'cat', '12');
INSERTINTO`pilipa_dds`.`student` (`id`, `name`, `age`) VALUES ('2', 'dog', '13');
INSERTINTO`pilipa_dds`.`student` (`id`, `name`, `age`) VALUES ('3', 'camel', '25');
INSERTINTO`pilipa_dds`.`student` (`id`, `name`, `age`) VALUES ('4', 'cat', '32');
INSERTINTO`pilipa_dds`.`student` (`id`, `name`, `age`) VALUES ('5', 'dog', '42');
目标:我们要去掉name相同的数据
先看看哪些数据重复了
SELECT name,count( 1 )
FROM
student
GROUP BY
NAME
HAVING
count( 1 ) > 1;
输出:
name count(1) cat 2 dog 2
name为cat和dog的数据重复了,每个重复的数据有两条;
Select * From 表 Where 重复字段 In (Select 重复字段 From 表 Group By 重复字段 Having Count(1)>1)
删除全部重复数据,一条不留
直接删除会报错
DELETE
FROM
student
WHERE
NAMEIN (
SELECTNAME
FROM
student
GROUPBY
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
NAMEIN (
SELECT
t.NAME
FROM
( SELECTNAMEFROM student GROUPBYNAMEHAVINGcount( 1 ) > 1 ) t)
删除表中删除重复数据,仅保留一条
在删除之前,我们可以先查一下,我们要删除的重复数据是啥样的
SELECT
*
FROM
student
WHERE
idNOTIN (
SELECT
t.id
FROM
( SELECTMIN( id ) ASidFROM student GROUPBY`name` ) t
)
开始删除重复数据,仅留一条
很简单,刚才的select换成delete即可
DELETE
FROM
student
WHERE
idNOTIN (
SELECT
t.id
FROM
( SELECTMIN( id ) ASidFROM student GROUPBY`name` ) t
)
文章转载:程序员老鬼
(版权归原作者所有,侵删)
点击下方“阅读原文”查看更多
关键词
效率
死锁
这个表
重复数据
了这个表
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。