查询和删除数据库表中有重复的数据,只保留唯一条记录的方法

来源:互联网 发布:淘宝化妆品销售排名 编辑:程序博客网 时间:2024/05/18 01:00

假设表结构为 CREATE TABLE tab_relation(num int, mb_id1 int , mb_id2 int, relation int, primary key(num)) ,mb_id1, mb_id2, relation3个字段表示两个用户的一种关系。

num为自增字段,具有唯一性

 

如果mb_id1, mb_id2, relation3有重复记录的情况,

1.可以通过如下SQL语句查询出来不重复的数据:

select * from tab_relation where num in
(select min(num) from tab_relation group by mb_id1, mb_id2, relation)

 

2.可以通过如下SQL语句删除掉多余的数据,只保留唯一数据:

delete  from tab_relation where num  not in
(select min(num) from tab_relation group by mb_id1, mb_id2, relation)

0 0