码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2018-10-04 10:10:07      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:update   style   name   let   复数   target   nbsp   src   where   

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删除重复数据只保留一条数据

标签:update   style   name   let   复数   target   nbsp   src   where   

原文地址:https://www.cnblogs.com/java-zzl/p/9739750.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!