如何在数据库里面用sql命令查询数据表里面的重复记录并删除多余的重复记录呢?
查询content字段的所有记录中内容相同的记录
如果我们要找出content字段,字段值内容重复的记录,sql命令可以按下面代码,这样查出来的结果,会将重复的记录做单次显示,默认显示较小的id记录:
select * from test where id in (select id from test group by content having count(content) > 1)
select * from test where content in (select content from test group by content having count(content) > 1);
Select content,Count(*) From test Group By content Having Count(*) > 1;
执行下面的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最大的重复记录:
THE END
喜欢就支持一下吧