mysql(16) : 根据多个字段删除重复数据

mysql 专栏收录该内容
34 篇文章 0 订阅

参考 : 

    https://blog.csdn.net/n950814abc/article/details/82284838

    https://www.cnblogs.com/liyue-sqsf/p/9076902.html

单个字段(CODE)

DELETE FROM `TEST` WHERE `ID` IN(
    SELECT * FROM(
        SELECT `ID` FROM `TEST` WHERE `CODE` IN (
            SELECT `CODE` FROM TEST GROUP BY `CODE` HAVING COUNT(*)> 1
        )
        AND `ID` NOT IN(
            SELECT MIN(`ID`)FROM TES GROUP BY `CODE` HAVING COUNT(*)> 1
        )
    ) T
);

多个字段(CODE,NAME)

DELETE FROM `TEST` WHERE `ID` IN(
    SELECT * FROM(
        SELECT `ID` FROM `TEST` WHERE (`CODE`,`NAME`) IN (
            SELECT `CODE`,`NAME` FROM `TEST` GROUP BY `CODE`,`NAME` HAVING COUNT(*)> 1
        )
        AND `ID` NOT IN(
            SELECT MIN(`ID`)FROM `TEST` GROUP BY `CODE`,`NAME` HAVING COUNT(*)> 1
        )
    ) T
);

低效率(该SQL一次只会删除重复的一条数据,需要执行n次,不推荐)

DELETE FROM `TEST` WHERE `ID` IN (
    SELECT * FROM (
        SELECT `ID`  FROM `TEST` GROUP BY `CODE` ,`NAME` HAVING COUNT(*) > 1
    )L
);

 

测试数据

1.表结构

CREATE TABLE `TEST` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `CODE` VARCHAR(32) DEFAULT NULL,
  `NAME` VARCHAR(32) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=INNODB AUTO_INCREMENT=20 DEFAULT CHARSET=UTF8;

2.测试数据

TRUNCATE TABLE `TEST`;
INSERT INTO `TEST`(`ID`,`CODE`,`NAME`) VALUES
(1,'C1','N1'),
(2,'C2','N2'),
(3,'C2','N2'),
(4,'C2','N21'),
(5,'C2','N21'),
(6,'C3','N3'),
(7,'C3','N3'),
(8,'C3','N3'),
(9,'C3','N31'),
(10,'C3','N31'),
(11,'C3','N31'),
(12,'C4','N4'),
(13,'C4','N4'),
(14,'C4','N4'),
(15,'C4','N4'),
(16,'C4','N41'),
(17,'C4','N41'),
(18,'C4','N41'),
(19,'C4','N41');

 

 

END。

  • 0
    点赞
  • 0
    评论
  • 4
    收藏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:书香水墨 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值