在mysql中删除重复记录我们有多种方法,下面我介绍利用临时表与ALTER IGNORE TABLE命令来实现,希望些方法对各位会有所帮助.
mysql删除字段重复的数据,经过搜索刚开始是这样做的:
- delete from v_togo
- where tel in (select tel from v_togo group by tel having count(tel) > 1)
- and togoid not in (select min(togoid) from v_togo group by tel having count(tel )>1)
结果mysql报错:you can't specify target table 'v_togo' for update in from clause
然后我是这样解决的,分三个步骤:
1、create table tmp as select max(togoid) as toid from v_togo group by tel;先把要处理的字段存储到临时表
2、delete from v_togo where togoid not in (select toid from tmp);根据临时表进行筛选
3、drop table tmp;删除临时表
例,我是想做一个去重复操作,比如,如下表:
- id title
-
- 1 张三
-
- 2 李四
-
- 3 张三
-
- 4 王五
-
- 5 李四
最终结果是:
- id title
-
- 1 张三
-
- 2 李四
-
- 4 王五
替换方案,代码如下:
- create table tmp as select min(id) as col1 from blur_article group by title;delete from blur_article where id not in (select col1 from tmp); drop table tmp;
已经测试,尽请使用这样就ok了,
或者这样操作,代码如下:
ALTER IGNORE TABLE `表名` ADD UNIQUE (`唯一索引字段名`);
删除重复的数据,只保留一条. |