SQL删除重复数据只保留一条数据

Posted 程序员自我修养张振力

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL删除重复数据只保留一条数据相关的知识,希望对你有一定的参考价值。

1、表结构与数据:

CREATE TABLE tablezzl(
id int,
name VARCHAR(255)
);

2、查询出重复的数据:

SELECT name FROM tablezzl GROUP BY name HAVING COUNT(name)>1

3、查询出要保留的重复数据:

SELECT MIN(id) ids FROM tablezzl GROUP BY NAME HAVING COUNT(name)>1

4、最终的SQL:

DELETE FROM tablezzl 
WHERE 1=1
    AND `name` in (SELECT * FROM ( (SELECT `name` `names` FROM tablezzl GROUP BY name HAVING COUNT(`name`)>1) ) a)
    AND id not in (SELECT * FROM ( (SELECT MIN(id) ids FROM tablezzl GROUP BY NAME HAVING COUNT(`name`)>1) ) b)

5、补充 : 

  其中这样写mysql中不能如下这样写:

DELETE FROM tablezzl 
WHERE 1=1
AND `name` in (SELECT `name` `names` FROM tablezzl GROUP BY name HAVING COUNT(`name`)>1) 
AND id not in (SELECT MIN(id) ids FROM tablezzl GROUP BY NAME HAVING COUNT(`name`)>1) 

会报错:You can\'t specify target table \'tablezzl\' for update in FROM clause,不能在同一表中查询的数据作为同一表的更新数据,如模块4的SQL包装一下就可以解决。

 

以上是关于SQL删除重复数据只保留一条数据的主要内容,如果未能解决你的问题,请参考以下文章

SQL删除重复数据只保留一条

SQL删除重复数据只保留一条数据

数据库怎样删除多条重复数据保留一条?

SQL删除重复数据只保留一条

SQL删除重复数据只保留一条

怎么删除ACCESS中的重复记录 只保留一条