爱亚搏 > 只使用一条sql语句,删除表中的重复记录

只使用一条sql语句,删除表中的重复记录

分类: sql ?|? 作者: zzm628 相关 ?|? 发布日期 : 2016-06-11 ?|? 热度 : 5°

一个表,表1,ref(唯一值),type(有重复)如何去掉重复记录。

建表sql语句:

-- ----------------------------
-- Table structure for `deletechongfu`
-- ----------------------------
DROP TABLE IF EXISTS `deletechongfu`;
CREATE TABLE `deletechongfu` (
? `id` int(11) NOT NULL AUTO_INCREMENT,
? `ref` int(11) DEFAULT NULL,
? `type` int(11) DEFAULT NULL,
? PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;


-- ----------------------------
-- Records of deletechongfu
-- ----------------------------
INSERT INTO `deletechongfu` VALUES ('1', '1', '2');
INSERT INTO `deletechongfu` VALUES ('2', '2', '4');
INSERT INTO `deletechongfu` VALUES ('3', '3', '4');
INSERT INTO `deletechongfu` VALUES ('4', '4', '5');
INSERT INTO `deletechongfu` VALUES ('5', '5', '5');
INSERT INTO `deletechongfu` VALUES ('6', '6', '5');
INSERT INTO `deletechongfu` VALUES ('7', '7', '7');
INSERT INTO `deletechongfu` VALUES ('8', '8', '7');
INSERT INTO `deletechongfu` VALUES ('9', '9', '5');


实现方法如下:

DELETE FROM deletechongfu WHERE id not in(SELECT a.id FROM (SELECT id FROM deletechongfu GROUP BY type) a);

mysql中必须通过一个临时表才能实现。


请参考:http://www.aiuxian.com/article/p-3296214.html