Delete duplicate data in different id, and a duplicate data retention

- construction of the table, insert test data

DROP TABLE IF EXISTS `table1`;
CREATE TABLE `table1` (
`id` int(11) NULL DEFAULT NULL,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of table1
-- ----------------------------
INSERT INTO `table1` VALUES (1, 'A');
INSERT INTO `table1` VALUES (2, 'B');
INSERT INTO `table1` VALUES (3, 'C');
INSERT INTO `table1` VALUES (4, 'D');
INSERT INTO `table1` VALUES (5, 'E');
INSERT INTO `table1` VALUES (6, 'A');

SET FOREIGN_KEY_CHECKS = 1;

- All data
SELECT * FROM table1

 

 

- packet data query, the query does not have to duplicate data ID
the SELECT min (ID) the FROM table1 the GROUP BY name

 

 

-- 执行删除,若提示> 1093 -- You can't specify target table 'table1' for update in FROM clause
DELETE from table1 where id not in
(SELECT min(id) FROM table1 GROUP BY name)

 

 

- use the following sql, jacket query, the query result and
the DELETE WHERE ID Not in table1 from
(SELECT * from (
the SELECT min (ID) AS the FROM table1 the GROUP BY name ID) A
)

 

Guess you like

Origin www.cnblogs.com/liyunchuan/p/12593948.html