日期:2014-05-16  浏览次数:20772 次

MySQL_用一条SQL语句删除重复记录

?

MySQL 一条SQL语句删除重复记录

?

不正确的写法一。

delete from t_user where id in(select max(id) as id from t_user group by username );?

但是mysql不支持这个写法(别的db是不是支持,没有测试),报错:

ERROR 1093 (HY000): You can't specify target table 't_user' for update in FROM clause

原因大概是删除的同时,不能查询自己,跟程序的foreach循环过程中不能删除类似

?

不正确的写法二。

delete t_user

from t_user as t_user, (select id from t_user group by username having count(*) > 1) as t2

where t_user.id=t2.id;?

这个的原理是删除重复的,但这个算法只对重复个数是2的管用,一旦重复数是3等,就不能惯用了。

?

?

正确的方法一。

--这个算法的原理是:group但不会count,这样在temp_table中的就是最终要留下来的结果,把其他的删除就ok了

--另外,这里利用了temp table,避免了上面foreach不能删除的问题

delete t_user

from t_user ?

where id not in (

? ? select id from (select id from t_user group by username) as temp_table

);

?

正确的方法二。

算法同上,只是可以不用group,用distinct

?

例子:

--表

?

drop table t_user;?

create table t_user(?

id ? ? ? ?int(5) not null auto_increment,?

username varchar(10),?

age ? ? ? int(3),?

primary key(id)?

);?

?

--插入

insert into t_user(username,age) values('aaa',20);?

insert into t_user(username,age) values('aaa',20);

?

insert into t_user(username,age) values('bbb',20);?

insert into t_user(username,age) values('bbb',20);?

insert into t_user(username,age) values('bbb',20);?

?

insert into t_user(username,age) values('ccc',20);?

insert into t_user(username,age) values('ccc',20);?

insert into t_user(username,age) values('ccc',20);?

insert into t_user(username,age) values('ccc',20);?

insert into t_user(username,age) values('e',10);?

insert into t_user(username,age) values('f',5);?


--查看
mysql> select * from t_user;
+----+----------+------+
| id | username | age ?|
+----+----------+------+
| 55 | aaa ? ? ?| ? 20 |
| 56 | aaa ? ? ?| ? 20 |
| 57 | bbb ? ? ?| ? 20 |
| 58 | bbb ? ? ?| ? 20 |
| 59 | bbb ? ? ?| ? 20 |
| 60 | ccc ? ? ?| ? 20 |
| 61 | ccc ? ? ?| ? 20 |
| 62 | ccc ? ? ?| ? 20 |
| 63 | ccc ? ? ?| ? 20 |
| 64 | e ? ? ? ?| ? 10 |
| 65 | f ? ? ? ?| ? ?5 |
+----+----------+------+
11 rows in set (0.00 sec)

?

--删除

?

delete t_user

from t_user ?

where id not in (

? ? select id from (select id from t_user group by username) as temp_table

);

--再查看

?

mysql> select * from t_user;

+----+----------+------+

| id | username | age ?|

+----+----------+------+

| 55 | aaa ? ? ?| ? 20 |

| 57 | bbb ? ? ?| ? 20 |

| 60 | ccc ? ? ?| ? 20 |

| 64 | e ? ? ? ?| ? 10 |

| 65 | f ? ? ? ?| ? ?5 |

+----+----------+------+

5 rows in set (0.00 sec)


?

?

--------END EOF 完毕-------

O

K

?

O

K

O

K


?