test1
id c_id
1 0013
2 0014
3 0013
4 0013我只是查询就没反应了,表的记录在5千以上。我用的查询命令是:
select * from test1 where c_id in (
select id from test1
group by c_id
having count(c_id) > 1
)怎么把相同c_id的记录删除掉,保留id最小的一个,最好是效率高的语句。如果是多个字段相同呢,语句又该怎么写?
id c_id
1 0013
2 0014
3 0013
4 0013我只是查询就没反应了,表的记录在5千以上。我用的查询命令是:
select * from test1 where c_id in (
select id from test1
group by c_id
having count(c_id) > 1
)怎么把相同c_id的记录删除掉,保留id最小的一个,最好是效率高的语句。如果是多个字段相同呢,语句又该怎么写?
where a.c_id in
(select c_id from test1 group by c_id having count(*) > 1)
and a.id not in (select min(id) from test1 group by c_id having count(*)>1)下面这个是有多个字段相同的例子,方便你以后遇到时可以解决:
delete from vitae a
where (a.peopleId,a.seq) in
(select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)
delete from test1 a where a.id not in (select min(id) from test1 group by c_id);/*单字段的重复合并*/
delete from test1 a where a.id not in (select min(id) from test1 group by field1,field2);/*多字段的重复合并*/
delete from test1 a where a.id not in (select min(id) from test1 order by field1,field2 group by field1,field2);/*多字段的重复合并*/
delete from test1 a where a.id not in (select min(id) from (select * from test1 order by field1,field2)as tb group by field1,field2);/*多字段的重复合并*/
+------+------+
| id | c_id |
+------+------+
| 1 | 0013 |
| 2 | 0014 |
| 3 | 0013 |
| 4 | 0013 |
+------+------+
4 rows in set (0.06 sec)
mysql> delete t from test1 t left join
-> (select c_id,min(id) as min_id from test1 group by c_id) t1
-> on t.id=t1.min_id
-> where t1.min_id is null;
Query OK, 2 rows affected (0.06 sec)mysql> select * from test1;
+------+------+
| id | c_id |
+------+------+
| 1 | 0013 |
| 2 | 0014 |
+------+------+
2 rows in set (0.00 sec)mysql>
这句里面t,t1是什么意思?