`

删除重复数据

 
阅读更多
看个实际例子:将表test中的userName重复的记录删掉:


 
 上面的例子不太全面有bug,因为如果userName相同但是height不同的话会被误删。所以应该这样:


 
 
********************************************************************************************
mysql> select * from duplicate;
+----+-------+
| id | name  |
+----+-------+
|  1 | wang  | 
|  2 | wang  | 
|  3 | wdang | 
|  4 | wdang | 
|  5 | wdand | 
|  6 | wddda | 
+----+-------+
6 rows in set (0.00 sec)
select * from duplicate where id in(select min(id) from duplicate group by name);
+----+-------+
| id | name  |
+----+-------+
|  1 | wang  | 
|  3 | wdang | 
|  5 | wdand | 
|  6 | wddda | 
+----+-------+
4 rows in set (0.01 sec)
mysql> delete from duplicate where id not in(select min(id) from duplicate group by name);
ERROR 1093 (HY000): You can't specify target table 'duplicate' for update in FROM clause
 
错误原因:
mysql中不能这么用。 (等待mysql升级吧)
错误提示就是说,不能先select出同一表中的某些值,再update这个表(在同一语句中) 

替换方案: 
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); 
  • 大小: 58.1 KB
  • 大小: 245.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics