如何在数据库里面用sql命令查询数据表里面的重复记录并删除多余的重复记录呢?
![图片[1] - sql查询重复记录并删除多余重复记录的方法 - 尘心网](https://m.cx9.cn/wp-content/uploads/2022/04/a0cc4f9e2fdd.jpg)
查询content字段的所有记录中内容相同的记录
如果我们要找出content字段,字段值内容重复的记录,sql命令可以按下面代码,这样查出来的结果,会将重复的记录做单次显示,默认显示较小的id记录:
select * from test where id in (select id from test group by content having count(content) > 1)
![图片[2] - sql查询重复记录并删除多余重复记录的方法 - 尘心网](https://m.cx9.cn/wp-content/uploads/2022/04/9c2adcf52bbf.jpg)
select * from test where content in (select content from test group by content having count(content) > 1);
![图片[3] - sql查询重复记录并删除多余重复记录的方法 - 尘心网](https://m.cx9.cn/wp-content/uploads/2022/04/1c3dee799409.jpg)
Select content,Count(*) From test Group By content Having Count(*) > 1;
![图片[4] - sql查询重复记录并删除多余重复记录的方法 - 尘心网](https://m.cx9.cn/wp-content/uploads/2022/04/e473059bacaa.jpg)
执行下面的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最大的重复记录:
![图片[5] - sql查询重复记录并删除多余重复记录的方法 - 尘心网](https://m.cx9.cn/wp-content/uploads/2022/04/9006e0fe8c38.jpg)
THE END
喜欢就支持一下吧