mysql 中删除重复字段数据的方式
1、创建一张表
CREATE TABLE `user` ( `id` int(11) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, `address` varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2、插入对应数据
INSERT INTO `user` VALUES ('1', 'zhangsan', '20', '上海'); INSERT INTO `user` VALUES ('2', 'zhangsan', '20', '北京'); INSERT INTO `user` VALUES ('3', 'lisi', '25', '北京'); INSERT INTO `user` VALUES ('4', 'lisi', '25', '深圳'); INSERT INTO `user` VALUES ('5', 'wangwu', '30', '深圳'); INSERT INTO `user` VALUES ('6', 'wangwu', '30', '上海'); INSERT INTO `user` VALUES ('7', 'zhaoliu', '35', '广州');
3、常用操作
#复制一张表 CREATE TABLE `user` as SELECT * FROM `user_temp` #创建一张空表 CREATE TABLE user_temp1 like `user` #删除一张表 DROP TABLE `user`
4、使用借助count关键字
DELETE FROM `user` WHERE id in( SELECT v.minid FROM( SELECT COUNT(*) num,`name`,age,MAX(id) minid FROM `user` GROUP BY `name`,age ) v WHERE v.num>1 )
5、使用having关键字
DELETE FROM `user` WHERE id in( SELECT id FROM( SELECT MAX(id) id,`name`,age,address FROM `user` t GROUP BY t.`name` HAVING COUNT(`name`)>1 ) v )
注意:delete语句直接删除一条查询结果集是行不通的,必须借助内嵌视图也就是字查询来完成删除功能