--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*/
目前,您不能从一个表中删除,同时又在子查询中从同一个表中选择。
可以利用distinct关键字对需要处理的字段进行去重
使用group by关键字对去重数据进行去重查询,针对某个字段查询,直接group by 这个字段
在group by 的基础上 也可以使用 having 对查询结果进行二次筛选
SELECT count(id), id, `user`, dengji FROM TESTGROUP BY `user`, dengji HAVING COUNT(id) > 1
DELETE FROM TEST WHERE id IN()
先查出重复的记录,然后一条一条删掉,当然你也可以做个子查询,一条SQL就好,不过第一条SQL很耗性能生成环境下,还是 慎用
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)