如何在数据库里面用sql命令查询数据表里面的重复记录并删除多余的重复记录呢?

上面的这个表test,有两个字段id和content,共7条记录,可以看到id=1、2、3时,content字段的值都是aaa,id=6、7时,content字段的值都为eee。
查询content字段的所有记录中内容相同的记录
如果我们要找出content字段,字段值内容重复的记录,sql命令可以按下面代码,这样查出来的结果,会将重复的记录做单次显示,默认显示较小的id记录:
select * from test where id in (select id from test group by content having count(content) > 1)

将重复的数据全部显示出来,可以用以下的sql语句:
select * from test where content in (select content from test group by content having count(content) > 1);

还可以用下面的sql语句来将记录重复的次数展示出来:
Select content,Count(*) From test Group By content Having Count(*) > 1;

删除content字段内容重复的多余的记录
执行下面的sql语句即可删除前面表test里面的多余的重复记录,仅保留id最大的重复记录。
DELETE FROM test
WHERE id NOT IN
(SELECT nd.i FROM
(SELECT MAX(id) as i FROM test GROUP BY content HAVING COUNT(*) > 1
UNION
SELECT MAX(id) as i FROM test GROUP BY content HAVING COUNT(*) = 1) as nd
)
sql语句解释:
主要是下面这一段代码:
下面的nd是临时表别名,i是临时字段别名,下面的as完全可以省略掉,不影响命令执行的。
SELECT nd.i FROM
(SELECT MAX(id) as i FROM test GROUP BY content HAVING COUNT(*) > 1
UNION
SELECT MAX(id) as i FROM test GROUP BY content HAVING COUNT(*) = 1) as nd
我们现在数据库里面执行,可以看到这段代码主要是将content内容重复的id排除掉,剩下的是去重完了的id3、4、5、7,保留了id最大的重复记录:

评论