mysql实用优化笔记(二):查询出重复记录并去重

建表语句

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL,
  `identity_no` varchar(20) NOT NULL,
  `name` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 

 

插入数据

INSERT INTO `t_user` VALUES ('1', '320000198903231581', '张三');
INSERT INTO `t_user` VALUES ('2', '130100199209082007', '李四');
INSERT INTO `t_user` VALUES ('3', '000000000000', '王五');
INSERT INTO `t_user` VALUES ('4', '320000198903231581', '张三');
INSERT INTO `t_user` VALUES ('5', '320000198903231581', '张三');
INSERT INTO `t_user` VALUES ('6', '130100199209082007', '李四');

查询identity_no重复所有记录

select * from t_user where identity_no in
   (select identity_no From t_user group by identity_no having count(*)>1);

去除identity_no重复记录(保留id小的记录)

DELETE FROM t_user WHERE id IN (
   SELECT * FROM (
       SELECT id FROM t_user where identity_no IN(SELECT identity_no  FROM t_user GROUP BY identity_no HAVING COUNT(identity_no)>1)
       AND id NOT IN (SELECT MIN(id) FROM t_user GROUP BY identity_no HAVING COUNT(identity_no) >1) 
   )AS tmp
);

你可能感兴趣的:(Mysql)