MYSQL 删除表中重复数据
CREATE TABLE `test` ( `id` int(11) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `dept` varchar(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of test -- ---------------------------- INSERT INTO `test` VALUES ('1', 'zzz', '测试1'); INSERT INTO `test` VALUES ('2', 'www', '测试1'); INSERT INTO `test` VALUES ('3', 'fff', '测试1'); INSERT INTO `test` VALUES ('4', 'zzz', '测试1'); INSERT INTO `test` VALUES ('5', 'www', '测试1'); INSERT INTO `test` VALUES ('6', 'fff', '测试1'); INSERT INTO `test` VALUES ('7', 'test', '测试1'); INSERT INTO `test` VALUES ('8', 'test', '测试1'); INSERT INTO `test` VALUES ('9', 'test1', '测试1');
可以看到上述表中id为4,5,6,8 是完全重复的数据,我们需要删除这些数据,我的逻辑是什么呢,就是每条数据分组后 取 id 最小的 那个 留下来,其余的进行删除
SQL如下:
DELETE FROM test WHERE id NOT IN ( SELECT t.id FROM ( SELECT min(id) id FROM test GROUP BY NAME HAVING count(1) > 0 ORDER BY id ) t )