-- 直接这样查,会报错。要用 中间表,起别名deletefrom 表 where 重复字段 in(select 重复字段 from 表 groupby 重复字段 havingcount(*)>1)DELETEFROM stu WHERE name IN(-- 注意:一定得用一个 中间表SELECT t1.name FROM(-- 查询出所有重复的user_nameSELECT name FROM stu GROUPBY name HAVINGCOUNT(1)>1) t1 -- 必须起别名)
保留一条记录
1. 使用 中间表(对于:表数据都相同)
-- 创建临时表createtable my_tmp like stu
-- 插入临时表里数据,去重后。 (没有ID的情况) insertinto my_tmp
selectdistinct*from stu
-- 删除原表droptable stu;-- 重命名 tmp 表为 sturenametable my_tmp to stu
2. 使用分组和嵌套 in 或 not in
表中的数据: id 和 name
1 1
3 2
2 2
查询出这条冗余的数据 2种方式
查出冗余的列
公式如下:
注意:查询是 不需要中间表的
select * from 表 where 重复字段 in (
select 重复字段 from 表 group by 重复字段 having count(*)>1
)
-- 查询的记过
3 2
2 2
-- 方式1
select * from stu where name in (
-- 查询出 冗余的 name
select name from stu group by name having count(1)>1
)
并且这个冗余的列 id不为最小
-- 并且: id 不为 最小的IDand id notin(-- 查询重复的 name 字段, 取最小的IDselectmin(id) name from stu groupby name havingcount(1)>1)-- 结果32
内层分组取最小,外层不为最小的ID
-- 方式2:-- id 不在 这里的 select*from stu where id notin(-- 查询出 最小的ID,根据name 分组,如果name 多个-- 只会返回一个selectmin(id)from stu groupby name
)SQL运行后
32
进行删除
方式1:上面的结果 使用中间表删除
max(id) 删除,id最大的
DELETEFROM stu WHERE id in(SELECT id FROM(-- 放上面的SQL) t -- 必须用中间表,并且起别名)-- 放上面的SQLselect*from stu where id notin(-- 查询出 最小的ID,根据name 分组,如果name 多个-- 只会返回一个selectmin(id)from stu groupby name
)
方式2:内层查重复的最小的id,外层不为这个id
deletefrom stu where id notin(-- 删除ID,不在这里面-- 包一层中间表select t.id from(selectmin(id) id from stu groupby name -- 根据name分组,取出最小的 id) t -- 起别名为 t)