MySQL去除表中重复数据

用户表users,表字段id,user_code,user_name,由于在开始建表的时候没有确定主键,导致该表中存在重复记录,如下表所示

id user_code user_name
1 001 Jame
2 001 Jame
3 001 Jame
4 001 Jame
5 001 Jame
6
请编写一个SQL语句,清除表中垃圾数据

1.首先查看重复数据

SELECT
	id,
	user_name,
	user_code,
FROM
	users 
GROUP BY
	user_name,
	user_code

注意:MySQL5.7以上默认开启了only_full_group_by模式,查询了非分组字段会报错
windows打开my.ini直接删掉only_full_group_by这一项即可
mac在my.cnf文件中下列代码到mysqld配置中
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
重启mysql服务就会生效

2.选择最小的id

SELECT 
	MIN(id) 
FROM 
	users 
GROUP BY 
	user_code, user_name

3.删除id不在最小id里的数据

DELETE 
FROM
	users 
WHERE
	id NOT IN ( SELECT MIN( id ) FROM users GROUP BY user_code, user_name )

直接写上面语句会报错,原因是:MySQL中不能同时查询和修改语句
所以需要加入中间表查询

DELETE 
FROM
	users 
WHERE
	id NOT IN ( SELECT temp.min_id FROM ( 
	SELECT MIN(id) min_id FROM users GROUP BY user_code, user_name 
	) AS temp)

你可能感兴趣的:(MySQL语句)