mysql 对某几个字段去重

mysql 对某几个字段去重
比如select id,a,b,c from table;
现在怎么对id,和a同时相同的字段去重。
用distinct只能对id,a,b,c全相同的去重,各位有什么好得办法没。

-------------------部分字段重复---------------------
--1.加索引的方式
create table test_2(id int,value int);
insert test_2 select 1,2 union all select 1,3 union all select 2,3;
Alter IGNORE table test_2 add primary key(id);
select * from test_2;
+----+-------+
| id | value |
+----+-------+
| 1 | 2 |
| 2 | 3 |
+----+-------+
我们可以看到 1 3 这条记录消失了
我们这里也可以使用Unique约束 因为有可能列中有NULL值,但是这里NULL就可以多个了..
--2.联合表删除
create table test_2(id int,value int);
insert test_2 select 1,2 union all select 1,3 union all select 2,3;
delete A from test_2 a join (select MAX(value) as v ,ID from test_2 group by id) b
on a.id=b.id and a.value<>b.v;
select * from test_2;
+------+-------+
| id | value |
+------+-------+
| 1 | 3 |
| 2 | 3 |
+------+-------+
--3.使用Increment_auto也可以就是上面全部字段去重的第二个方法
--4.容易错误的方法
--有些朋友可能会想到子查询的方法,我们来试验一下
create table test_2(id int,value int);
insert test_2 select 1,2 union all select 1,3 union all select 2,3;
delete a from test_2 a where exists(select * from test_2 where a.id=id and a.value<value);
/*ERROR 1093 (HY000): You can't specify target table 'a' for update in FROM clause*/

目前,您不能从一个表中删除,同时又在子查询中从同一个表中选择。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-12-02
分组下不就行了,delete from table where rowid not in (selelct max(rowid) from table group by id,a);
这样就把重复的数据删掉了。本回答被提问者和网友采纳
第2个回答  2010-12-02
提供个思路,用select a,b,c,count(distinct id) from table可以只对id相同的去重